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/plinko/lib/iscdr.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 CDR */ int IsCdr(int x_) { dword w_; if (x_ >= 0) return 0; w_ = Get(x_); // (⍆ X) int ax_ = LO(w_); int dx_ = HI(w_); if (ax_ != kCdr) 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/histo.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 "tool/plinko/lib/histo.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" void PrintHistogram(int fd, const char *s, const long *h, size_t n) { long t; bool islast; int j, p, m; char buf[101]; size_t i, logos; if (!(t = GetLongSum(h, n))) return; Fprintf(fd, "%s%n", s); for (i = 0; i < n; ++i) { if (!h[i]) continue; p = h[i] * 1000000 / t; assert(0 <= p && p <= 1000000); for (j = 0, m = p / 10000; j < m; ++j) { buf[j] = '#'; } buf[j] = 0; if (i) { logos = 1; logos <<= i - 1; } else { logos = 0; } islast = i == n - 1; Fprintf(fd, "%'16lu%s %'*ld %3d.%04d%% %s%n", logos, islast ? "+" : "", 16 - islast, h[i], p / 10000, p % 10000, buf); } }
2,639
51
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/trace.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/printf.h" #include "tool/plinko/lib/trace.h" void EnableTracing(void) { eval = EvalTrace; bind_ = BindTrace; evlis = EvlisTrace; pairlis = PairlisTrace; recurse = RecurseTrace; expand = mtrace ? ExpandTrace : Expand; kTail[0] = DispatchTailTrace; kTail[4] = DispatchTailTrace; kTail[5] = DispatchTailGcTrace; kTail[6] = DispatchTailTrace; kTail[7] = DispatchTailTmcGcTrace; } static inline int ShortenExpression(int e) { return e; } static bool AlwaysTrace(int e) { return true; } static bool LimitedTrace(int e) { return e < 0; } static relegated struct T TailTracer(dword ea, dword tm, dword r, dword p1, dword p2, TailFn *f) { if (depth < ARRAYLEN(g_depths)) { Fprintf(2, "%J╠═Tail[%p @ %d] p1=%S p2=%S δ %'Rns%n", ShortenExpression(LO(ea)), LO(ea), LO(p1), LO(p2)); } return f(ea, tm, r, p1, p2); } relegated struct T DispatchTailTrace(dword ea, dword tm, dword r, dword p1, dword p2) { return TailTracer(ea, tm, r, p1, p2, DispatchTail); } relegated struct T DispatchTailGcTrace(dword ea, dword tm, dword r, dword p1, dword p2) { return TailTracer(ea, tm, r, p1, p2, DispatchTailGc); } relegated struct T DispatchTailTmcGcTrace(dword ea, dword tm, dword r, dword p1, dword p2) { int x; if (depth < ARRAYLEN(g_depths)) { x = LO(tm); x = x < 0 ? x : ~x; Fprintf(2, "%J╟⟿Cons[%p @ %d] δ %'Rns%n", x, x); } return TailTracer(ea, tm, r, p1, p2, DispatchTailTmcGc); } static relegated int Trace(int e, int a, EvalFn *f, bool p(int), const char *s, const unsigned short c[5]) { int d, r, rp, S = sp; DCHECK_GE(depth, -1); d = depth; depth = MAX(d, 0); if (depth < ARRAYLEN(g_depths)) { if (p(e)) { if (loga) { Fprintf(2, "%I%c%c%s[e=%S @ %d; a=%S @ %d] δ %'Rns%n", c[0], c[1], s, ShortenExpression(e), e, a, a); } else { Fprintf(2, "%I%c%c%s[%S @ %d] δ %'Rns%n", c[0], c[1], s, ShortenExpression(e), e); } } g_depths[depth][0] = c[2]; g_depths[depth][1] = L' '; g_depths[depth][2] = L' '; } ++depth; r = f(e, a); --depth; if (depth < ARRAYLEN(g_depths) && p(e)) { rp = r != e ? r : kUnchanged; if (sp == S) { Fprintf(2, "%I%c%c%p @ %d %'Rns%n", c[3], c[4], rp, r); } else { Fprintf(2, "%I%c%c%p @ %d %'Rns [STACK SKEW S=%d vs. sp=%d]%n", c[3], c[4], rp, r, S, sp); } } depth = d; return r; } relegated int RecurseTrace(dword ea, dword p1, dword p2) { int r, d, S = sp; const char *s = "Recurse"; const unsigned short c[5] = u"╔═║╚═"; if (depth < ARRAYLEN(g_depths)) { if (loga) { Fprintf(2, "%I%c%c%s[LO(ea)=%S @ %d; HI(ea)=%S @ %d] p1=%S p2=%S δ %'Rns%n", c[0], c[1], s, ShortenExpression(LO(ea)), LO(ea), HI(ea), HI(ea), LO(p1), LO(p2)); } else { Fprintf(2, "%I%c%c%s[%S @ %d] p1=%S p2=%S δ %'Rns%n", c[0], c[1], s, ShortenExpression(LO(ea)), LO(ea), LO(p1), LO(p2)); } g_depths[depth][0] = c[2]; g_depths[depth][1] = L' '; g_depths[depth][2] = L' '; } ++depth; r = Recurse(ea, p1, p2); --depth; if (depth < ARRAYLEN(g_depths)) { if (r != LO(ea)) { Fprintf(2, "%I%c%c%p @ %d δ %'Rns%n", c[3], c[4], r, r); } else { Fprintf(2, "%I%c%cⁿ/ₐ δ %'Rns%n", c[3], c[4]); } } return r; } relegated int EvlisTrace(int e, int a, dword p1, dword p2) { int r, d, S = sp; const char *s = "Evlis"; const unsigned short c[5] = u"╒─┆╘─"; DCHECK_GE(depth, -1); d = depth; depth = MAX(d, 0); if (depth < ARRAYLEN(g_depths)) { if (loga) { Fprintf(2, "%I%c%c%s[e=%S @ %d; a=%S @ %d] δ %'Rns%n", c[0], c[1], s, ShortenExpression(e), e, a, a); } else { Fprintf(2, "%I%c%c%s[%S @ %d] δ %'Rns%n", c[0], c[1], s, ShortenExpression(e), e); } g_depths[depth][0] = c[2]; g_depths[depth][1] = L' '; g_depths[depth][2] = L' '; } ++depth; r = Evlis(e, a, p1, p2); --depth; if (depth < ARRAYLEN(g_depths)) { if (r != e) { Fprintf(2, "%I%c%c%p @ %d δ %'Rns%n", c[3], c[4], r, r); } else { Fprintf(2, "%I%c%cⁿ/ₐ δ %'Rns%n", c[3], c[4]); } } depth = d; return r; } relegated int Trace3(int x, int y, int a, PairFn *f, const char *s, const unsigned short c[5]) { int r, d, S = sp; if (depth < ARRAYLEN(g_depths)) { if (loga) { Fprintf(2, "%I%c%c%s[x=%S; y=%S; a=%S] δ %'Rns%n", c[0], c[1], s, ShortenExpression(x), ShortenExpression(y), a); } else { Fprintf(2, "%I%c%c%s[x=%S; y=%S] δ %'Rns%n", c[0], c[1], s, ShortenExpression(x), ShortenExpression(y)); } g_depths[depth][0] = c[2]; g_depths[depth][1] = L' '; g_depths[depth][2] = L' '; } ++depth; r = f(x, y, a); --depth; return r; } relegated struct Binding BindTrace(int x, int y, int a, int u, dword p1, dword p2) { int d, S = sp; struct Binding r; if (depth < ARRAYLEN(g_depths)) { if (loga) { Fprintf(2, "%I%c%c%s[x=%S; y=%S; a=%S; u=%S] δ %'Rns%n", L'╒', L'─', "Bind", ShortenExpression(x), ShortenExpression(y), a, u); } else { Fprintf(2, "%I%c%c%s[x=%S; y=%S] δ %'Rns%n", L'╒', L'─', "Bind", ShortenExpression(x), ShortenExpression(y)); } g_depths[depth][0] = L'┋'; g_depths[depth][1] = L' '; g_depths[depth][2] = L' '; } ++depth; r = Bind(x, y, a, u, p1, p2); --depth; return r; } int EvalTrace(int e, int a) { return Trace(e, a, Eval, AlwaysTrace, "Eval", u"╔═║╚═"); } int ExpandTrace(int e, int a) { return Trace(e, a, Expand, LimitedTrace, "Expand", u"┌─│└─"); } int PairlisTrace(int x, int y, int a) { return Trace3(x, y, a, Pairlis, "Pairlis", u"╒─┊╘─"); }
7,976
232
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/cons.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" #include "tool/plinko/lib/cons.h" int List(int x, int y) { return Cons(x, Cons(y, -0)); } int List3(int x, int y, int z) { return Cons(x, List(y, z)); } int List4(int a, int b, int c, int d) { return Cons(a, List3(b, c, d)); } int Shadow(int p, int s) { int t = GetCommonCons(p, s); return t ? t : Cons(p, s); } int GetCommonCons(int x, int y) { if (!y) { if (!x) return -1; if (x > 0 && cFrost < -1 && IsUpper(LO(Get(x))) && HI(Get(x)) == TERM) { return kConsAlphabet[LO(Get(x)) - L'A']; } } return 0; } int ShareCons(int x, int y) { dword t; int i, n; if ((i = GetCommonCons(x, y))) return i; #if 0 t = MAKE(x, y); for (i = cx, n = MIN(0, i + 64); i < n; ++i) { if (t == Get(i)) { return i; } } #endif return Cons(x, y); } int ShareList(int x, int y) { return ShareCons(x, ShareCons(y, -0)); }
2,737
67
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/findfreevariables.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" /** * Finds free variables in expression. * * @param e is expression * @param r is atom list result accumulator * @param s is atom tree of shadowed bindings * @return atom list of crash bindings without duplicates * @note this produces garbage when recursing into let */ int FindFreeVariables(int e, int r, int s) { int f, t; if (e >= 0) { if (!IsConstant(e) && !HasAtom(e, s) && !HasAtom(e, r)) { t = GetCommonCons(e, r); r = t ? t : Cons(e, r); } } else { f = Car(e); if (f != kQuote && f != kClosure) { if (f == kLambda || f == kMacro) { r = FindFreeVariables(Caddr(e), r, Shadow(Cadr(e), s)); } else if (f == kCond) { while ((e = Cdr(e)) < 0) { if ((f = Car(e)) < 0) { r = FindFreeVariables(Car(f), r, s); if ((f = Cdr(f)) < 0) { r = FindFreeVariables(Car(f), r, s); } } } } else { while (e) { if (e < 0) { f = Car(e); e = Cdr(e); } else { f = e; e = 0; } r = FindFreeVariables(f, r, s); } } } } return r; }
3,126
69
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/ktpenc.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. │ ╚─────────────────────────────────────────────────────────────────────────────*/ const short kTpEnc[25] = {0140001, 0140001, 0140001, 0140001, 0160002, 0160002, 0160002, 0160002, 0160002, 0170003, 0170003, 0170003, 0170003, 0170003, 0174004, 0174004, 0174004, 0174004, 0174004, 0176005, 0176005, 0176005, 0176005, 0176005, 0176005};
2,193
25
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/assoc.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/histo.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/tree.h" /** * Performs lookup of binding. * * We perform lookups into an association list, e.g. * * ┌───┬───┐ ┌───┬───┐ ┌───┬───┐ * │ 𝑘₀│ 𝑣₀│ │ 𝑘₁│ 𝑣₁│ │ 𝑘₂│ 𝑣₂│ * └─┬─┴───┘ └─┬─┴───┘ └─┬─┴───┘ * ┌─│─┬───┐ ┌─│─┬───┐ ┌─│─┬───┐ * 𝑎=│ ┴ │ ├───┤ ┴ │ ├───┤ ┴ │ 0 │ * └───┴───┘ └───┴───┘ └───┴───┘ * * For example, if 𝑘₁ is queried then we return: * * ┌───┬───┐ * │ 𝑘₁│ 𝑣₁│ * └───┴───┘ * * However there's a twist: the association is allowed to turn into a * red-black tree. That would look like this: * * ┌───┬───┐ ┌───┬───┐ * │ 𝑘₀│ 𝑣₀│ │ 𝑘₁│ 𝑣₁│ * └─┬─┴───┘ └─┬─┴───┘ * ┌─│─┬───┐ ┌─│─┬───┐ ┌───┬───┐ * 𝑎=│ ┴ │ ├───┤ ┴ │ ├───│ ┬ │ 𝑐 │ * └───┴───┘ └───┴───┘ └─│─┴───┘ * ┌─┴─┬───┐ * │ ┬ │ ┬ │ * └─│─┴─│─┘ * ┌───┬──┴┐ ┌┴──┬───┐ * │ 𝑘₂│ 𝑣₂│ │ L │ R │ * └───┴───┘ └───┴───┘ * * We're able to tell a tree node apart from an association list node * because we make the assumption that 𝑘ᵢ is an atom. On the other hand * 𝑣ᵢ can be anything. * * @param k is an atom * @param a is an association list and/or red-black tree * @return entry cons cell or 0 if not found */ int Assoc(int k, int a) { int i, j, e, c, r; DCHECK_GE(k, 0); i = a; r = 0; if (k && k != 1) { for (c = 0; i;) { e = Head(i); i = Cdr(i); j = Head(e); ++c; if (j == k) { r = e; break; } else if (j < 0 && (j = #if HISTO_ASSOC GetTreeCount(k, e, &c) #else GetTree(k, e) #endif )) { r = Ent(j); break; } } #if HISTO_ASSOC HISTO(g_assoc_histogram, c); #endif } return r; }
4,612
97
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/tree.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/tree.h" int Nod(int E, int L, int R, int C) { #ifndef NDEBUG DCHECK_LE(L, 0); DCHECK_LE(R, 0); DCHECK_EQ(0, C & ~1); #endif return Cons(Cons(E, (L | R) ? Cons(L, R) : 0), C); } static void CheckTreeImpl(int N) { int p, e, L, R; if (N >= 0) Error("N is atom: %S", N); if (Car(N) >= 0) Error("Car(N) is an atom: %S", N); if (Cdr(N) & ~1) Error("Cdr(N) is non-bool: %S", N); if ((L = Lit(N))) { if ((p = Cmp(Key(Ent(L)), Key(Ent(N)))) != -1) { Error("Cmp(Key(L), Key(N)) != -1%n" "Result = %d%n" "Key(L) = %p%n" "Key(N) = %p", p, Key(Ent(L)), Key(Ent(N))); } if (Red(N) && Red(L)) { Error("left node and its parent are both red%n%T", N); } CheckTreeImpl(L); } if ((R = Rit(N))) { if ((p = Cmp(Key(Ent(R)), Key(Ent(N)))) != +1) { Error("Cmp(Key(R), Key(N)) != +1%n" "Result = %d%n" "Key(R) = %p%n" "Key(N) = %p", p, Key(Ent(R)), Key(Ent(N))); } if (Red(N) && Red(R)) { Error("right node and its parent are both red%n%T", N); } CheckTreeImpl(R); } } static int CheckTree(int N) { #if DEBUG_TREE if (N) { if (Red(N)) Error("tree root is red%n%T", N); CheckTreeImpl(N); } #endif return N; } static int BalTree(int E, int L, int R, int C) { // Chris Okasaki "Red-Black Trees in a Functional Setting"; // Functional Pearls, Cambridge University Press, Jan 1993. int LL, LR, RL, RR; if (!C) { LL = Lit(L); LR = Rit(L); RL = Lit(R); RR = Rit(R); if (Red(L) && Red(LR)) { // Degenerate Case No. 1 // Complete the Triforce // // Z // ╱ ╲ 𝐘 // 𝐗 d ╱ ╲ // ╱ ╲ → X Z // a 𝐘 ╱ ╲ ╱ ╲ // ╱ ╲ a b c d // b c // // ((Z ((X a (Y b . c) . t) . t) . d)) → // ((Y ((X a . b)) (Z c . d)) . t) L = Nod(Ent(L), LL, Lit(LR), 0); R = Nod(E, Rit(LR), R, 0); E = Ent(LR); C = 1; } else if (Red(L) && Red(LL)) { // Degenerate Case No. 2 // Complete the Triforce // // Z // ╱ ╲ 𝐘 // 𝐘 d ╱ ╲ // ╱ ╲ → X Z // 𝐗 c ╱ ╲ ╱ ╲ // ╱ ╲ a b c d // a b // // ((Z ((Y ((X a . b) . t) . c) . t) . d)) → // ((Y ((X a . b)) (Z c . d)) . t) R = Nod(E, LR, R, 0); E = Ent(L); L = Bkn(LL); C = 1; } else if (Red(R) && Red(RR)) { // Degenerate Case No. 3 // Complete the Triforce // // X // ╱ ╲ 𝐘 // a 𝐘 ╱ ╲ // ╱ ╲ → X Z // b 𝐙 ╱ ╲ ╱ ╲ // ╱ ╲ a b c d // c d // // ((X a (Y b (Z c . d) . t) . t)) → // ((Y ((X a . b)) (Z c . d)) . t) L = Nod(E, L, RL, 0); E = Ent(R); R = Bkn(RR); C = 1; } else if (Red(R) && Red(RL)) { // Degenerate Case No. 4 // Complete the Triforce // // X // ╱ ╲ 𝐘 // a 𝐙 ╱ ╲ // ╱ ╲ → X Z // 𝐘 d ╱ ╲ ╱ ╲ // ╱ ╲ a b c d // b c // // ((X a (Z ((Y b . c) . t) . d) . t)) → // ((Y ((X a . b)) (Z c . d)) . t) L = Nod(E, L, Lit(RL), 0); R = Nod(Ent(R), Rit(RL), RR, 0); E = Ent(RL); C = 1; } } return Nod(E, L, R, C); } static int InsTree(int E, int N, int KEEP) { int P, L, R; if (N) { P = Cmp(Key(E), Key(Ent(N))); if (P < 0) { if ((L = InsTree(E, Lit(N), KEEP)) > 0) return L; // rethrow if (L != Lit(N)) N = BalTree(Ent(N), L, Rit(N), Tail(N)); } else if (P > 0) { if ((R = InsTree(E, Rit(N), KEEP)) > 0) return R; // rethrow if (R != Rit(N)) N = BalTree(Ent(N), Lit(N), R, Tail(N)); } else if (KEEP < 0 || (!KEEP && !Equal(Val(E), Val(Ent(N))))) { N = Cons(Cons(E, Chl(N)), Red(N)); } else if (KEEP > 1) { N = KEEP; // throw } } else { N = Cons(Cons(E, 0), 1); } return N; } /** * Inserts entry into red-black tree. * * DICTIONARY NODE SET NODE ATOM SET NODE * * ┌───┬───┐ ┌───┬───┐ ┌───┬───┐ * │ ┬ │ 𝑐 │ │ ┬ │ 𝑐 │ │ ┬ │ 𝑐 │ * └─│─┴───┘ └─│─┴───┘ └─│─┴───┘ * ┌─┴─┬───┐ ┌─┴─┬───┐ ┌─┴─┬───┐ * │ ┬ │ ┬ │ │ ┬ │ ┬ │ │ 𝑣 │ ┬ │ * └─│─┴─│─┘ └─│─┴─│─┘ └───┴─│─┘ * ┌───┬──┴┐ ┌┴──┬───┐ ┌───┬──┴┐ ┌┴──┬───┐ ┌─┴─┬───┐ * │ 𝑥 │ 𝑦 │ │ L │ R │ │ 𝑥 │ ⊥ │ │ L │ R │ │ L │ R │ * └───┴───┘ └───┴───┘ └───┴───┘ └───┴───┘ └───┴───┘ * * @param E is entry which may be * - (𝑥 . 𝑦) where 𝑥 is the key and 𝑦 is arbitrary tag-along content * - 𝑣 for memory-efficient sets of atoms * @param N is red-black tree node which should look like * - ⊥ is an tree or atom set with zero elements * - (((𝑥 ⋯) . (𝑙 . 𝑟)) . ⊥) is a black node a.k.a. (((𝑥 ⋯) 𝑙 . 𝑟)) * - (((𝑥 ⋯) . (𝑙 . 𝑟)) . ⊤) is a red node a.k.a. (((𝑥 ⋯) 𝑙 . 𝑟) . ⊤) * - ((𝑣 𝑙 . 𝑟)) a memory-efficient black node for an atom set * - ((𝑣 𝑙 . 𝑟)) is functionally equivalent to (((𝑣) 𝑙 . 𝑟)) * - ((𝑣 ⊥ . ⊥)) is an atom set with a single element * - ((𝑣)) is functionally equivalent to ((𝑣 ⊥ . ⊥)) or ((𝑣 . (⊥ . ⊥)) . ⊥) * - 𝑣 is crash therefore (((⋯) 𝑣)) and ⊥(((⋯) ⊥ . 𝑣)) are crash * - (𝑣) is crash, first element must be a cons cell * - ((⋯) . 𝑥) is crash if 𝑥 isn't ⊤ or ⊥ * @param KEEP may be * - -1 to replace existing entries always * - 0 to replace existing entries if values are non-equal * - 1 to return N if * - >1 specifies arbitrary tombstone to return if key exists * @return ((𝑒 𝑙 . 𝑟) . 𝑐) if found where 𝑒 can be 𝑣 or (𝑥 . 𝑦) * - or KEEP if not found and KEEP > 1 * - or ⊥ if not found */ int PutTree(int E, int N, int KEEP) { DCHECK_LE(N, 0); DCHECK_LE(Car(N), 0); DCHECK_GE(KEEP, -1); return CheckTree(Bkn(InsTree(E, N, KEEP))); } /** * Finds node in binary tree. * @return ((𝑒 𝑙 . 𝑟) . 𝑐) if found, otherwise 0 */ int GetTree(int k, int N) { int p, e; while (N) { p = Cmp(k, Key(Ent(N))); if (p < 0) { N = Lit(N); } else if (p > 0) { N = Rit(N); } else { break; } } return N; } int GetTreeCount(int k, int N, int *c) { int p, e; while (N) { ++*c; p = Cmp(k, Key(Ent(N))); if (p < 0) { N = Lit(N); } else if (p > 0) { N = Rit(N); } else { break; } } return N; }
9,643
261
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/define.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 │ │ │ │ Copying of this file is authorized only if (1) you are Justine Tunney, or │ │ (2) you make absolutely no changes to your copy. │ │ │ │ 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/cons.h" #include "tool/plinko/lib/gc.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/tree.h" void GetName(int *x) { int t; if (*x < 0) { if ((t = GetTree(*x, revglob))) { *x = Val(Ent(t)); } } } int Define(int e, int a) { struct Gc *G; int k, v, x, r, o; DCHECK_EQ(kDefine, Car(e)); if (Cdr(e) >= 0) Error("bad define: %S", e); if (Cadr(e) <= 0) Error("scheme define: %S", e); if (Cddr(e) >= 0 || Caddr(e) == kLambda) { /* * compatibility with sectorlisp friendly branch, e.g. * * (DEFINE 𝑘 . 𝑣) * (DEFINE 𝑘 . (LAMBDA ⋯)) * * are equivalent to the following * * (DEFINE 𝑘 (QUOTE 𝑣)) * (DEFINE 𝑘 (QUOTE (LAMBDA ⋯))) */ e = Cdr(e); k = Car(e); } else if (!Cdddr(e)) { k = Cadr(e); v = Caddr(e); x = eval(v, a); e = Cons(k, x); } else { Error("too many args: %S", e); } a = Cons(PutTree(e, Car(a), 0), 0); r = PutTree(Cons(Cdr(e), Car(e)), revglob, 0); o = Cons(k, ordglob); G = NewGc(cFrost); Mark(G, a); Mark(G, r); Mark(G, o); Census(G); a = Relocate(G, a); r = Relocate(G, r); o = Relocate(G, o); Sweep(G); revglob = r; ordglob = o; return a; } /** * Prints stuff declared by Define(). * * The output is primarily intended for describing the internal machine * state, with a focus on readability. If closures are printed, with -c * then each nugget can be copied back into the machine on its own, b/c * each definition is a transitive closure that totally defines all its * dependencies. However it's quite verbose, so the normal mode is just * readable and can be finessed back into a good program with some work * although one thing that's really cool is it peels away macros in the * hope it can help demystify amazingly dense recreational abstractions * * @param t is symbol to use for DEFINE * @param a is an association list and/or red-black tree * @param o is ordering of names * @see Assoc() for documentation on structure of 𝑎 */ int DumpDefines(int t, int a, int o) { int e; bool nn; nn = noname; noname = true; for (; o; o = Cdr(o)) { e = Assoc(Car(o), a); Printf("%n%p%n", Cons(t, Cons(Car(e), Cons(Cdr(e), -0)))); } noname = nn; return 0; }
4,124
109
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/print.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" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/tree.h" int PrintDot(int fd) { return PrintChar(fd, L'.'); } int PrintSpace(int fd) { return PrintChar(fd, L' '); } void PrintNewline(int fd) { PrintChar(fd, L'\n'); } int PrintIndent(int fd, int n) { int i; for (i = 0; n > 0; --n) { i += PrintSpace(fd); } return i; } int PrintZeroes(int fd, int n) { int i; for (i = 0; n > 0; --n) { i += PrintChar(fd, L'0'); } return i; } int PrintDepth(int fd, int n) { int i, j; for (j = i = 0; n > 0; --n, ++j) { if (j < ARRAYLEN(g_depths)) { i += PrintChar(fd, g_depths[j][0]); i += PrintChar(fd, g_depths[j][1]); i += PrintChar(fd, g_depths[j][2]); } } return i; } int PrintListDot(int fd, int x) { int n; n = PrintSpace(fd); n += PrintDot(fd); n += PrintSpace(fd); n += Print(fd, x); return n; } bool ShouldForceDot(int x) { return Cdr(x) < 0 && (Car(Cdr(x)) == kClosure || Car(Cdr(x)) == kLambda || Car(Cdr(x)) == kMacro); } bool ShouldConcealClosure(int x) { return !logc && (Car(x) == kClosure /* && Cdr(x) < 0 && Car(Cdr(x)) < 0 && */ /* Car(Car(Cdr(x))) == kLambda && CountAtoms(x, 256, 0) >= 256 */); } int PrintList(int fd, int x) { int 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)); } n += PrintChar(fd, L'('); if (x < 0) { n += Print(fd, Car(x)); if (ShouldForceDot(x)) { n += PrintListDot(fd, Cdr(x)); } else { while ((x = Cdr(x))) { if (x < 0) { n += PrintSpace(fd); n += Print(fd, Car(x)); } else { n += PrintListDot(fd, x); break; } } } } n += PrintChar(fd, L')'); } return n; } bool HasWeirdCharacters(int x) { int c; dword e; do { e = Get(x); c = LO(e); x = HI(e); if (c == L'`' || c == L'"' || c == L'\'' || IsSpace(c) || IsParen(c) || IsSpace(c) || IsLower(c) || IsC0(c)) { return true; } } while (x != TERM); return false; } int PrintString(int fd, int x) { dword e; int c, u, n; n = PrintChar(fd, L'"'); do { e = Get(x); c = LO(e); x = HI(e); DCHECK_GT(c, 0); DCHECK_LT(c, TERM); if (c < 0200) { u = c; c = L'\\'; switch (c) { CASE(L'\a', c |= L'a' << 010); CASE(L'\b', c |= L'b' << 010); CASE(00033, c |= L'e' << 010); CASE(L'\f', c |= L'f' << 010); CASE(L'\n', c |= L'n' << 010); CASE(L'\r', c |= L'r' << 010); CASE(L'\t', c |= L't' << 010); CASE(L'\v', c |= L'v' << 010); CASE(L'\\', c |= L'\\' << 010); CASE(L'"', c |= L'"' << 010); default: if (32 <= c && c < 127) { c = u; } else { c |= ((L'0' + c / 8 / 8 % 8) << 010 | (L'0' + c / 8 % 8) << 020 | (L'0' + c % 8) << 030); } break; } do { n += PrintChar(fd, c & 255); } while ((c >>= 010)); } else { n += PrintChar(fd, c); } } while (x != TERM); n += PrintChar(fd, L'"'); return n; } int PrintAtom(int fd, int x) { dword e; int c, n = 0; DCHECK_GE(x, 0); if (x == 0) { if (symbolism && !literally) { n += PrintChar(fd, L'⊥'); } else { n += PrintChar(fd, L'N'); n += PrintChar(fd, L'I'); n += PrintChar(fd, L'L'); } } else if (x == 1) { if (symbolism && !literally) { n += PrintChar(fd, L'⊤'); } else { n += PrintChar(fd, L'T'); } } else if (x >= TERM) { n += PrintChar(fd, L'!'); n += PrintInt(fd, x, 0, 0, 0, 10, true); } else if (symbolism && (c = Symbolize(x)) != -1) { n += PrintChar(fd, c); } else { if (!literally && HasWeirdCharacters(x)) { n += PrintString(fd, x); } else { do { e = Get(x); c = LO(e); n += PrintChar(fd, c); } while ((x = HI(e)) != TERM); } } return n; } int EnterPrint(int x) { #if 0 int i; if (x < 0) { DCHECK_GE(pdp, 0); DCHECK_LT(pdp, ARRAYLEN(g_print)); if (x < 0) { for (i = 0; i < pdp; ++i) { if (x == g_print[i]) { x = kCycle; break; } } } g_print[pdp++] = x; if (pdp == ARRAYLEN(g_print)) { x = kTrench; } } #endif return x; } void LeavePrint(int x) { #if 0 if (x < 0) { --pdp; } #endif } int Print(int fd, int x) { int n; GetName(&x); x = EnterPrint(x); if (1. / x < 0) { n = PrintList(fd, x); } else { n = PrintAtom(fd, x); } LeavePrint(x); return n; }
6,718
256
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/isif.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 * * (ζ (X Y) (Z)) * * @return MAKE4(X,Y,Z,0) on success, or ZERO4 on mismatch * @note ζ means COND */ struct qword IsIf(int x_) { dword w_; if (x_ >= 0) return ZERO4; w_ = Get(x_); // (ζ (X Y) (Z)) int ax_ = LO(w_); int dx_ = HI(w_); if (ax_ != kCond) return ZERO4; if (dx_ >= 0) return ZERO4; w_ = Get(dx_); // ((X Y) (Z)) int adx_ = LO(w_); int ddx_ = HI(w_); if (adx_ >= 0) return ZERO4; w_ = Get(adx_); // (X Y) int aadx_ = LO(w_); int dadx_ = HI(w_); if (ddx_ >= 0) return ZERO4; w_ = Get(ddx_); // ((Z)) int addx_ = LO(w_); int dddx_ = HI(w_); int X = aadx_; if (addx_ >= 0) return ZERO4; w_ = Get(addx_); // (Z) int aaddx_ = LO(w_); int daddx_ = HI(w_); if (dadx_ >= 0) return ZERO4; w_ = Get(dadx_); // (Y) int adadx_ = LO(w_); int ddadx_ = HI(w_); if (dddx_) return ZERO4; int Y = adadx_; int Z = aaddx_; if (ddadx_) return ZERO4; if (daddx_) return ZERO4; return MAKE4(X, Y, Z, 0); }
2,867
64
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-format.el
;;; cosmo-format.el --- Cosmopolitan Clang-Format Integration ;; Author: Justine Tunney <[email protected]> ;; Version: 0.1.0 ;; License: Public Domain ;; Keywords: c c++ clang ;; To the extent possible under law, Justine Tunney has waived all ;; copyright and related or neighboring rights to this file, as it is ;; written in the following disclaimers: <http://unlicense.org/> and ;; <http://creativecommons.org/publicdomain/zero/1.0/> ;;; Commentary: ;; ;; This module automates indentation, whitespace, and other stylistic ;; concerns while editing C/C++ source files. The clang-format program, ;; if present on the system, is run each time a buffer is saved. ;;; Installation: ;; ;; Put the following in your .emacs.d/init.el file: ;; ;; (require 'cosmo-format) ;; ;; Put this file in the root of your project: ;; ;; printf '---\nBasedOnStyle: Google\n...\n' >.clang-format ;; ;; Any buffer whose pathname matches `cosmo-format-path-regex' will ;; be formatted automatically on save if: ;; ;; 1. It's able to find the clang-format program, or ;; `cosmo-format-bin' is customized. ;; ;; 2. There's a .clang-format file up the directory tree, or ;; `cosmo-format-arg' is customized; in which case, it is ;; recommended that it be customized buffer locally. ;; ;; For all other cases, there are no latency penalties (i.e. superfluous ;; i/o syscalls) or risks to leaving this enabled globally. ;;; Code: (defcustom cosmo-format-bin nil "Explicit command or pathname of clang-format program." :type 'string :group 'cosmo-format) (defcustom cosmo-format-arg nil "Explicit argument to clang-format program." :type 'string :group 'cosmo-format) (defcustom cosmo-format-modes '(c-mode c++-mode java-mode protobuf-mode) "List of major-modes that need clang-format." :type '(repeat symbol) :group 'cosmo-format) (defcustom cosmo-format-exts '("c" "cc" "h" "inc" ;; c/c++ "hh" "cpp" "hpp" ;; ms c/c++ "rl" ;; ragel "proto") ;; protobuf "List of pathname extensions that need clang-format." :type '(repeat string) :group 'cosmo-format) (defcustom cosmo-format-blacklist '("quickjs.c" "ggml.c") "List of files to ignore, matched by basename." :type '(repeat string) :group 'cosmo-format) (defvar cosmo--clang-format-bin) (defmacro cosmo-memoize (var mvar form) "Return VAR or evaluate FORM memoized locally to MVAR." `(cond (,var ,var) ((fboundp (quote ,mvar)) (cond ((eq ,mvar 'null) nil) (t ,mvar))) (t (let ((res ,form)) (setq-local ,mvar (or res 'null)) res)))) (defun cosmo--find-clang-format-bin () (cosmo-memoize cosmo-format-bin cosmo--clang-format-bin (or (executable-find "clang-format-10") (executable-find "clang-format-9") (executable-find "clang-format-8") (executable-find "clang-format-7") (executable-find "clang-format")))) (defun cosmo-format () "Beautifies source code in current buffer." (interactive) (when (and (memq major-mode cosmo-format-modes) (member (file-name-extension (buffer-file-name)) cosmo-format-exts) (not (member (file-name-nondirectory (buffer-name)) cosmo-format-blacklist)) (not (save-excursion (beginning-of-buffer) (looking-at "/\\* clang-format off \\*/")))) (let* ((bin (cosmo--find-clang-format-bin)) (this (buffer-file-name)) (root (locate-dominating-file this ".clang-format"))) (when (and bin root) (let ((p (point)) (tmp (make-temp-file "cosmo-format")) (arg1 (concat "--assume-filename=" (file-relative-name this root))) (arg2 (or cosmo-format-arg "-style=file"))) (when arg2 (write-region nil nil tmp) (let ((buf (get-buffer-create "*clang-format*")) (exe (cosmo--find-clang-format-bin))) (with-current-buffer buf (call-process exe tmp t nil arg1 arg2)) (replace-buffer-contents buf) (kill-buffer buf) (delete-file tmp nil)))))))) ;; Emacs 26.3+ needed for replace-buffer-contents; so worth it!! (unless (version-list-< (version-to-list emacs-version) '(26 3)) (add-hook 'before-save-hook 'cosmo-format)) (provide 'cosmo-format) ;;; cosmo-format.el ends here
4,785
134
jart/cosmopolitan
false
cosmopolitan/tool/emacs/ctest-mode.el
(defconst ctest-operators '("+" "-" "*" "/" "%" "//" "**" "~" "^" "|" "&" ">>" "<<" "!" "||" "&&" "=" "!=" "<" ">" "<=" ">=")) (defconst ctest-consts '("false" "true" "e" "pi" "epsilon" "inf" "nan" "l2t" "lg2" "ln2" "l2e")) (defconst ctest-builtins '("emit" "exit" "meminfo" "isnan" "isinf" "signbit" "isfinite" "isnormal" "fpclassify")) (defconst ctest-functions '("emit" "cr" "key" "dup" "swap" "over" "drop" "expect" "assert" "abs" "min" "max")) (defconst ctest-functions-libm '("mod" "rem" "gray" "ungray" "popcnt" "sqrt" "exp" "exp2" "exp10" "ldexp" "log" "log2" "log10" "sin" "cos" "tan" "asin" "acos" "atan" "atan2" "round" "trunc" "rint" "nearbyint" "ceil" "floor" "rand" "rand64")) (defun ctest--make-regex (words) (concat "\\_<" (regexp-opt words) "\\_>")) (defconst ctest-highlights `(("\\(#.*\\)$" 1 font-lock-comment-face) ("\\b0\\([xX]\\)[[:xdigit:]]+\\([ulUL]*\\)\\b" (1 font-lock-constant-face) (2 font-lock-constant-face)) ("\\b0\\([bB]\\)[01]+\\([ulUL]*\\)\\b" (1 font-lock-constant-face) (2 font-lock-constant-face)) (,(concat "\\_<" (regexp-opt ctest-consts) "\\_>") . font-lock-constant-face) (,(concat "\\_<" (regexp-opt ctest-builtins) "\\_>") . font-lock-builtin-face))) (define-derived-mode ctest-mode fundamental-mode "CALCULATOR.COM" "Major mode for editing CALCULATOR.COM smoke tests." (setq font-lock-defaults '(ctest-highlights))) (add-to-list 'auto-mode-alist '("\\.ctest$" . ctest-mode)) (provide 'ctest-mode)
1,823
116
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo.el
(require 'ctest-mode) (require 'ld-script) (require 'optinfo-mode) (require 'protobuf-mode) (require 'cosmo-format) (require 'cosmo-asm-mode) (require 'cosmo-stuff) (provide 'cosmo)
182
9
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-c-builtins.el
(defconst cosmo-c-builtins-regex (let ( (c11 '("static_assert")) (gcc-cpp-92-builtin-defines '("__VA_OPT__" "__COUNTER__" "__SIG_ATOMIC_TYPE__" "__INT8_TYPE__" "__INT16_TYPE__" "__INT32_TYPE__" "__INT64_TYPE__" "__UINT8_TYPE__" "__UINT16_TYPE__" "__UINT32_TYPE__" "__UINT64_TYPE__" "__INT_LEAST8_TYPE__" "__INT_LEAST16_TYPE__" "__INT_LEAST32_TYPE__" "__INT_LEAST64_TYPE__" "__UINT_LEAST8_TYPE__" "__UINT_LEAST16_TYPE__" "__UINT_LEAST32_TYPE__" "__UINT_LEAST64_TYPE__" "__INT_FAST8_TYPE__" "__INT_FAST16_TYPE__" "__INT_FAST32_TYPE__" "__INT_FAST64_TYPE__" "__UINT_FAST8_TYPE__" "__UINT_FAST16_TYPE__" "__UINT_FAST32_TYPE__" "__UINT_FAST64_TYPE__" "__INTPTR_TYPE__" "__UINTPTR_TYPE__" "__TIMESTAMP__" "__SANITIZE_ADDRESS__" "__SANITIZE_UNDEFINED__" "__FP_FAST_FMA" "__FP_FAST_FMAF" "__FP_FAST_FMAL")) (gcc-builtin-types '("__builtin_va_list")) (gcc-builtin-functions '("__builtin_add_overflow" "__builtin_add_overflow_p" "__builtin_alloc" "__builtin_alloca" "__builtin_alloca_with_align" "__builtin_alloca_with_align_and_max" "__builtin_apply" "__builtin_apply_args" "__builtin_assume" "__builtin_assume_aligned" "__builtin_bswap16" "__builtin_bswap32" "__builtin_bswap64" "__builtin_call_with_static_chain" "__builtin_choose_expr" "__builtin_clz" "__builtin_clzl" "__builtin_clzll" "__builtin_constant_p" "__builtin_ctz" "__builtin_ctzl" "__builtin_ctzll" "__builtin_expect" "__builtin_expect_with_probability" "__builtin_extract_return_addr" "__builtin_isnan" "__builtin_signbit" "__builtin_signbitf" "__builtin_signbitl" "__builtin_ffs" "__builtin_ffsl" "__builtin_ffsll" "__builtin_fma" "__builtin_fpclassify" "__builtin_frame_address" "__builtin_frob_return_addr" "__builtin_has_attribute" "__builtin_mul_overflow" "__builtin_mul_overflow_p" "__builtin_object_size" "__builtin_offsetof" "__builtin_popcount" "__builtin_popcountl" "__builtin_popcountll" "__builtin_prefetch" "__builtin_return" "__builtin_return_address" "__builtin_sub_overflow" "__builtin_sub_overflow_p" "__builtin_trap" "__builtin_types_compatible_p" "__builtin_unreachable" "__has_attribute" "__has_builtin" "__has_cpp_attribute" "__has_feature" "__ATOMIC_RELAXED" "__ATOMIC_CONSUME" "__ATOMIC_ACQUIRE" "__ATOMIC_RELEASE" "__ATOMIC_ACQ_REL" "__ATOMIC_SEQ_CST")) (gcc-builtin-functions-atomic '("__atomic_load_n" "__atomic_load" "__atomic_store" "__atomic_store_n" "__atomic_exchange_n" "__atomic_exchange" "__atomic_compare_exchange_n" "__atomic_compare_exchange" "__atomic_add_fetch" "__atomic_sub_fetch" "__atomic_and_fetch" "__atomic_xor_fetch" "__atomic_or_fetch" "__atomic_nand_fetch" "__atomic_fetch_add" "__atomic_fetch_sub" "__atomic_fetch_and" "__atomic_fetch_xor" "__atomic_fetch_or" "__atomic_fetch_nand" "__atomic_test_and_set" "__atomic_clear" "__atomic_thread_fence" "__atomic_signal_fence" "__atomic_always_lock_free" "__atomic_is_lock_free")) (gcc-builtin-functions-sync '("__sync_fetch_and_add" "__sync_fetch_and_sub" "__sync_fetch_and_or" "__sync_fetch_and_and" "__sync_fetch_and_xor" "__sync_fetch_and_nand" "__sync_add_and_fetch" "__sync_sub_and_fetch" "__sync_or_and_fetch" "__sync_and_and_fetch" "__sync_xor_and_fetch" "__sync_nand_and_fetch" "__sync_bool_compare_and_swap" "__sync_val_compare_and_swap" "__sync_synchronize" "__sync_lock_test_and_set" "__sync_lock_release")) (gcc-builtin-functions-ia32 '("__builtin_ia32_pmovmskb128")) (gxx-builtin-type-traits '("__has_nothrow_assign" "__has_trivial_assign" "__has_nothrow_copy" "__has_trivial_copy" "__has_nothrow_constructor" "__has_trivial_constructor" "__is_pod" "__has_trivial_destructor" "__has_virtual_destructor" "__is_abstract" "__is_base_of" "__is_class" "__is_empty" "__is_enum" "__is_literal_type" "__is_polymorphic" "__is_standard_layout" "__is_trivial" "__is_union" "__underlying_type" "__integer_pack" "__is_same")) (cosmopolitan-builtin-defines '("COSMOPOLITAN_CXX_START_" "COSMOPOLITAN_CXX_END_" "COSMOPOLITAN_CXX_USING_" "COSMOPOLITAN_C_START_" "COSMOPOLITAN_C_END_" "MACHINE_CODE_ANALYSIS_BEGIN_" "MACHINE_CODE_ANALYSIS_END_" "__VSCODE_INTELLISENSE__")) (cosmopolitan-builtin-functions '("DebugBreak" "VEIL" "CONCEAL" "EXPROPRIATE" "YOINK" "STATIC_YOINK" "PYTHON_YOINK" "PYTHON_PROVIDE" "STRINGIFY")) ) (concat "\\_<" (regexp-opt (append c11 gcc-cpp-92-builtin-defines gcc-builtin-types gcc-builtin-functions gcc-builtin-functions-atomic gcc-builtin-functions-sync gcc-builtin-functions-ia32 gxx-builtin-type-traits cosmopolitan-builtin-defines cosmopolitan-builtin-functions)) "\\_>"))) (provide 'cosmo-c-builtins)
6,874
221
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-asm-mode.el
;; ╔──────────────────────────────────────────────────────────────────╗ ;; │ To the extent possible under law, Justine Tunney has waived │ ;; │ all copyright and related or neighboring rights to this file, │ ;; │ as it is written in the following disclaimers: │ ;; │ • http://unlicense.org/ │ ;; │ • http://creativecommons.org/publicdomain/zero/1.0/ │ ;; ╚──────────────────────────────────────────────────────────────────╝ ;; Reconfigures GNU Emacs syntax highlighting for GNU Assembler syntax. (require 'asm-mode) (require 'cosmo-cpp-constants) (defun cosmo-regexpify (x) (let ((join (lambda (sep lis) (mapconcat 'identity lis sep)))) (cond ((vectorp x) (funcall join "" (mapcar 'cosmo-regexpify x))) ((listp x) (concat "\\(?:" (funcall join "\\|" (mapcar 'cosmo-regexpify x)) "\\)")) ('t x)))) (defun cosmo-fontify (faces regexp limit predicate) "Set FACES on REGEXP matches until LIMIT that satisfy PREDICATE." (while (re-search-forward regexp limit t) (let (i (face (save-excursion (backward-char) (face-at-point))) (syntax (syntax-ppss))) (when (funcall predicate face syntax) (dolist (i faces) (put-text-property (match-beginning (car i)) (match-end (car i)) 'face (cdr i))))))) (defconst asm-mode-gas-qualifiers-regexp (cosmo-regexpify [("comdat" ":req" ":vararg" ["@" (;; calculates offset relative to tls block end ;; load: mov %fs:boop@tpoff,%eax ;; addr: mov %fs:0,%rax ;; lea x1@tpoff(%rax),%rax ;; addr: mov %fs:0,%rax ;; add $x1@tpoff,%rax "tpoff" ;; allocates TLS_index structure ;; lea x@tlsgd(,%rbx,1),%rdi ;; call __tls_get_addr@plt "tlsgd" "tlsld" "dtpmod" "dtpoff" "gottpoff" "function" "object" "got" "size" "gotoff" "plt" "pltoff" "gotpcrel" "progbits" "nobits" "init_array" "fini_array")]) "\\>"]) "GNU Assembler section, relocation, macro param qualifiers.") (defconst asm-mode-doctag-regexp (cosmo-regexpify '(["<" ("p" "br" "b" "/b" "i" "/i" "pre" "/pre" "h3" "h4" "/h3" "/h4" "ul" "ol" "li" "/ol" "/ul" "dl" "dt" "dd" "/dl" "table" "tr" "td" "th" "td" "/table") ">"] ["@" ("param" "return" "define" "see" "throws" "returnstwice" "fileoverview" "nullable" "noreturn" "domain" "clob" "since" "forcealignargpointer" "mode" "speed" "cost" "todo" "assume" "define" "domain" "code" "note" "protip" "nxbitsafe" "vforksafe" "threadsafe" "preinitsafe" "asyncsignalsafe" "notasyncsignalsafe" "isa" "norestart" "mayalias" "sideffect") "\\>"])) "Assembly docstring highlighting in Google Java Style.") (defconst asm-mode-x86-prefix-ops-regexp (cosmo-regexpify [(["[lL][oO][cC][kK]\\>[ \t]*" ("[mM][oO][vV][sS]" "[aA][dD][dDcC]" "[sS][uUbB][bB]" "[oO][rR]" "[aA][nN][dD]" "[xX][oO][rR]" "[nN][oO][tT]" "[nN][eE][gG]" "[iI][nN][cC]" "[dD][eE][cC]" "[bB][tT][sSrRcC]?" "[xX][aA][dD][dD]" "[xX][cC][hH][gG]" ["[cC][mM][pP][xX][cC][hH][gG]" ("8[bB]" "16[bB]") "?"])] ["[rR][eE][pP]" ("[eEzZ]" "[nN][eEzZ]") "?\\>[ \t]*" ("[mM][oO][vV][sS]" "[sS][tT][oO][sS]" "[sS][cC][aA][sS]" "[cC][mM][pP][sS]" "[nN][oO][pP]" "[rR][eE][tT]" "[iI][nN][sS]" "[oO][uU][tT][sS]")]) "[bBwWlLqQ]?\\>"]) "Legal high-level 80x86 prefix instruction combinations.") (defconst cosmo-asm-font-lock-keywords (append `(;; AT&T Fortran-Style Assembler Comment ;; ;; - Valid ;; ;; * /heyho ;; * //heyho ;; ;; - Ignored ;; ;; *  /heyho ;; * code code //heyho ;; ("^/.*$" . font-lock-comment-face) ;; Immediate Argument ;; ;; - Valid ;; ;; * mov $2,%eax ;; * mov $~2+0x2ul,%eax ;; * mov $'c,%eax ;; * mov $'\n,%eax ;; ("[ \t,]\\$\\(\\(?:'\\(?:'\\|\\s\"\\|\\s\\.\\|.\\)\\|\\(?:0x[[:xdigit:]]+\\|0b[01]+\\|[1-9][0-9]*\\|0[0-7]*\\)\\(?:[fb]\\|u?l?l?\\)\\|[-*/&^|()%<>~+]\\|[_.$[:alpha:]][-_.[:alnum:]]*\\)+\\)" 1 font-lock-constant-face) (cosmo-asm-doctag-keywords) ;; Static Branch Prediction ;; ;; - Valid ;; ;; * jnz,pt 1f ;; * jnz,pn 1b ;; ;; - Traditionally Implied ;; ;; * jnz,pn 1f ;; * jnz,pt 1b ;; (",p[tn]" . font-lock-keyword-face) ("\\\\\\(?:@\\|()\\)" . font-lock-function-name-face) ("\\\\\\(\\sw\\|_\\|\\.\\)+\\>" . font-lock-variable-name-face) (,asm-mode-x86-prefix-ops-regexp . font-lock-keyword-face) (,(concat "^\\(\\(?:\\sw\\|\\s_\\|\\.\\)+\\):[ \t]*" "\\(\\(?:\\sw\\|\\.\\)+\\)?") (1 font-lock-function-name-face) (2 font-lock-keyword-face nil t)) ("^\\((\\sw+)\\)?\\s +\\(\\(\\.?\\sw\\|\\s_\\)+\\(\\.\\sw+\\)*\\)" 2 font-lock-keyword-face) ("^\\(\\.\\(\\sw\\|\\s_\\|\\.\\)+\\)\\>[^:]?" 1 font-lock-keyword-face) ("^.*?\\*/\\(\\.\\(\\sw\\|\\s_\\|\\.\\)+\\)\\>[^:]?" 1 font-lock-keyword-face) ;; it's complicated (,asm-mode-gas-qualifiers-regexp . font-lock-type-face)) cpp-font-lock-keywords `(("'\\(\\\\?.\\)\\>" 1 font-lock-constant-face) ;; Register Value ;; ;; - Valid ;; ;; * %al ;; * %eax ;; ;; - Ignored ;; ;; * %%al ;; ("%\\sw+" . font-lock-variable-name-face) ;; Hexadecimal Literal ;; ;; - Valid ;; ;; * 0x0123456789abcdef ;; * 0XDEADBEEFu ;; * -0xdeadbeefULL ;; ;; - Ignored ;; ;; * 0x0123456789abcdefg ;; ("\\b\\(0[xX]\\)[[:xdigit:]]+\\([ulUL]*\\)\\b" (1 font-lock-constant-face) (2 font-lock-constant-face)) ;; Binary Literal ;; ;; - Valid ;; ;; * 0b0101101101 ;; * 0B0101101101u ;; * -0b0101101101ULL ;; ;; - Ignored ;; ;; * 0b012 ;; ("\\b\\(0[bB]\\)[01]+\\([ulUL]*\\)\\b" (1 font-lock-constant-face) (2 font-lock-constant-face)) ;; Octal Literal ;; ;; - Valid ;; ;; * 01234567 ;; * 01234567l ;; * -01234567ULL ;; ;; - Ignored ;; ;; * 012345678 ;; ("\\b\\(0\\)[0-7]+\\([ulUL]*\\)\\b" (1 font-lock-constant-face) (2 font-lock-constant-face)) ;; Builtin Constants ;; ;; - Valid ;; ;; * 123456789 ;; * 123456789l ;; * -01234567ULL ;; ;; - Ignored ;; ;; * 123456789a ;; * 123456789aul ;; ("\\b[1-9][0-9]+\\([ulUL]*\\)\\b" 1 font-lock-constant-face) ;; AT&T Fortran-Style Assembler Comment ;; ;; - Valid ;; ;; * /heyho ;; * //heyho ;; ;; - Ignored ;; ;; *  /heyho ;; * code code //heyho ;; ("^/.*$" . font-lock-comment-face) ;; AT&T-Style Directional Label ;; ;; - Valid ;; ;; * 1f ;; * 99b ;; ("\\b\\([0-9]+\\)[fb]\\b" 1 font-lock-function-name-face))) "Additional expressions to highlight in Assembler mode.") (defun cosmo-asm-doctag-keywords (limit) (cosmo-fontify '((0 . font-lock-constant-face)) asm-mode-doctag-regexp limit (lambda (face syntax) (or (memq face '(font-lock-comment-face)) (and syntax (nth 4 syntax)))))) (defun cosmo-asm-supplemental-hook () "GNU Assembly in Bell Laboratories Style." (setq asm-comment-char ?¯) ;; Was ESR using TASM? (font-lock-add-keywords 'asm-mode '((cosmo-asm-doctag-keywords)) 'append) (set (make-local-variable 'require-final-newline) nil) (set (make-local-variable 'indent-tabs-mode) t) (set (make-local-variable 'tab-width) 8)) (progn (add-hook 'asm-mode-hook 'cosmo-asm-supplemental-hook) (setq asm-font-lock-keywords cosmo-asm-font-lock-keywords)) ;; Make -*-unix-assembly-*- mode line work correctly like GitHub. (define-derived-mode unix-assembly-mode asm-mode "UNIX Assembly") (provide 'cosmo-asm-mode)
9,376
344
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-c-types.el
(defconst cosmo-c-types-regex (let ( ;; (kar ;; '("short unsigned int" ;; "int" ;; "long unsigned int" ;; "char" ;; "long" ;; "long signed int" ;; "signed long" ;; "unsigned short int" ;; "short int" ;; "signed short int" ;; "unsigned" ;; "long unsigned" ;; "unsigned short" ;; "short signed int" ;; "short unsigned" ;; "unsigned char" ;; "signed int" ;; "unsigned long" ;; "long int" ;; "unsigned int" ;; "signed short" ;; "unsigned long int" ;; "short signed" ;; "signed long int" ;; "signed char" ;; "long signed")) (ansi '("size_t" "wint_t" ;; "void" "wchar_t" ;; "long double" )) ;; (kar ;; '("char" ;; "short" ;; "int" ;; "long" ;; "signed" ;; "unsigned")) ;; (ansi ;; '("size_t" ;; "wint_t" ;; "void" ;; "wchar_t")) (c99 '("bool" "_Bool" "unsigned long long int" "int32_t" "uint_least64_t" "long long signed" "intptr_t" "uintmax_t" "long long unsigned int" "int_fast32_t" "int16_t" "int64_t" "int_fast16_t" "int_fast64_t" "errno_t" "uint_fast32_t" "int_least8_t" "uint_least16_t" "long long signed int" "long long" "char16_t" "uint_least32_t" "int_least64_t" "int_least16_t" "int_fast8_t" "uint_least8_t" "uintptr_t" "ssize_t" "time_t" "long long int" "unsigned long long" "int8_t" "long long unsigned" "signed long long int" "int_least32_t" "uint8_t" "uint_fast64_t" "intmax_t" "uint_fast16_t" "signed long long" "uint32_t" "ptrdiff_t" "char32_t" "uint64_t" "uint16_t" "uint_fast8_t" "complex float" "complex double" "complex long double")) (c11 '("atomic_uintptr_t" "atomic_uchar" "atomic_int_least32_t" "atomic_uint_least64_t" "atomic_int_fast32_t" "atomic_uint_least16_t" "atomic_short" "atomic_size_t" "atomic_uint" "atomic_char16_t" "atomic_ullong" "atomic_uint_fast16_t" "atomic_int_fast8_t" "atomic_uint_least32_t" "atomic_ptrdiff_t" "atomic_uintmax_t" "atomic_int_least16_t" "atomic_long" "atomic_int" "atomic_int_fast16_t" "atomic_uint_least8_t" "atomic_ushort" "atomic_int_least8_t" "atomic_ulong" "atomic_char32_t" "atomic_schar" "atomic_intmax_t" "atomic_int_least64_t" "atomic_uint_fast64_t" "atomic_wchar_t" "atomic_uint_fast8_t" "atomic_int_fast64_t" "atomic_llong" "atomic_bool" "atomic_intptr_t" "atomic_uint_fast32_t" "atomic_char")) (gnu '("__int128" "unsigned __int128" "signed __int128" "_Float16" "_Complex _Float16" "_Float16x" "_Complex _Float16x" "_Float32" "_Complex _Float32" "_Float32x" "_Complex _Float32x" "_Float64" "_Complex _Float64" "_Float64x" "_Complex _Float64x" "_Float128" "_Complex _Float128")) (cxx17 '()) (cosmo '("int_least128_t" "int_fast128_t" "mbedtls_mpi_sint" "mbedtls_mpi_uint" "bool32" "int128_t" "uint128_t" "axdx_t")) (linux '("i8" "u8" "i16" "u16" "i32" "u32" "i64" "u64" "off_t" "rlim_t")) (x86intrin '("__v8hu" "__v16qi" "__v4su" "__v8su" "__v16qu" "__v16qs" "__v8hi" "__v4hi" "__v2df" "__v2di" "__v4si" "__v8si" "__m1" "__v2du" "__m2" "__v1di" "__v4sf" "__v8sf" "__v2si" "__m64" "__v2sf" "__v8qi" "__v32qi" "__m128" "__m128d" "__m128i" "__m128_u" "__m128d_u" "__m128i_u" "__m256" "__m256d" "__m256i" "__m256_u" "__m256d_u" "__m256i_u")) ) (concat "\\_<" (regexp-opt (append ;; kar ansi c99 c11 gnu cxx17 cosmo linux x86intrin)) "\\_>"))) (provide 'cosmo-c-types)
5,681
239
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-c-constants.el
(defconst cosmo-c-constants-ansi '("EOF" "WEOF" "NDEBUG" "HUGE_VAL" "HUGE_VALF" "HUGE_VALL" "CLK_TCK" "FLT_ROUNDS")) (defconst cosmo-c-constants-c11 '("__func__" "__VA_ARGS__" "__STDC__" "__STDC_HOSTED__" "__STDC_VERSION__" "__TIME__" "__STDC_ISO_10646__" "__STDC_MB_MIGHT_NEQ_WC__" "__STDC_UTF_16__" "__STDC_UTF_32__" "__STDC_ANALYZABLE__" "__STDC_IEC_559_COMPLEX__" "__STDC_LIB_EXT1__" "__STDC_NO_ATOMICS__" "__STDC_NO_COMPLEX__" "__STDC_NO_THREADS__" "__STDC_NO_VLA__" "__FLT_EVAL_METHOD__" "__STDC_WANT_LIB_EXT1__")) (defconst cosmo-c-constants-limits '("IMAGE_BASE_VIRTUAL" "IMAGE_BASE_REAL" "IMAGE_BASE_PHYSICAL" "CHAR_MAX" "SCHAR_MAX" "UCHAR_MAX" "SHRT_MAX" "INT_MAX" "LONG_MAX" "LLONG_MAX" "LONG_LONG_MAX" "SIZE_MAX" "SSIZE_MAX" "INT8_MAX" "INT16_MAX" "INT32_MAX" "INT64_MAX" "INT128_MAX" "WINT_MAX" "WCHAR_MAX" "INTPTR_MAX" "PTRDIFF_MAX" "SCHAR_MIN" "UCHAR_MIN" "SHRT_MIN" "UINT_MIN" "INT_MIN" "LONG_MIN" "LLONG_MIN" "LONG_LONG_MIN" "SIZE_MIN" "INT8_MIN" "INT16_MIN" "INT32_MIN" "INT64_MIN" "INT128_MIN" "INTMAX_MIN" "INTPTR_MIN" "WINT_MIN" "WCHAR_MIN" "PTRDIFF_MIN" "USHRT_MAX" "UINT_MAX" "ULONG_MAX" "ULLONG_MAX" "ULONG_LONG_MAX" "UINTPTR_MAX" "UINT8_MAX" "UINT16_MAX" "UINT32_MAX" "UINT64_MAX" "UINT128_MAX" "USHRT_MIN" "ULONG_MIN" "ULLONG_MIN" "ULONG_LONG_MIN" "UINT8_MIN" "UINT16_MIN" "UINT32_MIN" "UINT64_MIN" "UINT128_MIN" "UINTMAX_MIN" "UINTPTR_MIN" "MB_CUR_MAX" "MB_LEN_MAX" "INTMAX_MAX" "UINTMAX_MAX" "INTMAX_MAX" "UINTMAX_MAX" "DBL_MIN" "DBL_MAX" "FLT_MIN" "FLT_MAX" "PIPE_BUF")) (defconst cosmo-c-constants-math '("NAN" "INFINITY" "M_E" "M_LOG2_10" "M_LOG10_2" "M_LOG2E" "M_LOG10E" "M_LN2" "M_LN10" "M_TAU" "M_PI" "M_PI_2" "M_PI_4" "M_1_PI" "M_2_PI" "M_2_SQRTPI" "M_SQRT2" "M_SQRT1_2" "DBL_DECIMAL_DIG" "DBL_DIG" "DBL_EPSILON" "DBL_MANT_DIG" "DBL_MANT_DIG" "DBL_MAX" "DBL_MAX_10_EXP" "DBL_MAX_EXP" "DBL_MIN" "DBL_MIN_10_EXP" "DBL_MIN_EXP" "DECIMAL_DIG" "FLT_DECIMAL_DIG" "FLT_RADIX" "FLT_DIG" "FLT_EPSILON" "FLT_MANT_DIG" "FLT_MANT_DIG" "FLT_MAX" "FLT_MAX_10_EXP" "FLT_MAX_EXP" "FLT_MIN" "FLT_MIN_10_EXP" "FLT_MIN_EXP" "HLF_MAX" "HLF_MIN" "FLT_EVAL_METHOD" "LDBL_DECIMAL_DIG" "LDBL_DIG" "LDBL_EPSILON" "LDBL_MANT_DIG" "LDBL_MANT_DIG" "LDBL_MAX" "LDBL_MAX_10_EXP" "LDBL_MAX_EXP" "LDBL_MIN" "LDBL_MIN_10_EXP" "LDBL_MIN_EXP" "FP_NAN" "FP_INFINITE" "FP_ZERO" "FP_SUBNORMAL" "FP_NORMAL")) (defconst cosmo-c-constants-regex (concat "\\_<" (regexp-opt (append cosmo-c-constants-ansi cosmo-c-constants-c11 cosmo-c-constants-limits cosmo-c-constants-math)) "\\_>")) (provide 'cosmo-c-constants)
3,265
181
jart/cosmopolitan
false
cosmopolitan/tool/emacs/key.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os,sys,re kar_types = frozenset([ "char", "signed char", "unsigned char", "int", "signed", "signed int", "unsigned", "unsigned int", "short", "short int", "short signed", "short signed int", "short unsigned", "short unsigned int", "signed short", "signed short int", "unsigned short", "unsigned short int", "long", "long int", "long signed", "long signed int", "long unsigned", "long unsigned int", "signed long", "signed long int", "unsigned long", "unsigned long int", "float", "double", ]) ansi_types = frozenset([ "void", "wchar_t", "wint_t", "size_t", "long double", ]) c99_types = frozenset([ "long long", "long long int", "long long signed", "long long signed int", "long long unsigned", "long long unsigned int", "signed long long", "signed long long int", "unsigned long long", "unsigned long long int", "char16_t", "char32_t", "errno_t", "int8_t", "int16_t", "int32_t", "int64_t", "int_fast8_t", "int_fast16_t", "int_fast32_t", "int_fast64_t", "int_least16_t", "int_least32_t", "int_least64_t", "int_least8_t", "uint_fast16_t", "uint_fast32_t", "uint_fast64_t", "uint_fast8_t", "uint_least16_t", "uint_least32_t", "uint_least64_t", "uint_least8_t", "intmax_t", "intptr_t", "ptrdiff_t", "ssize_t", "uint16_t", "uint32_t", "uint64_t", "uint64_t", "uint8_t", "uintmax_t", "uintptr_t", ]) c11_types = frozenset([ "atomic_bool", "atomic_char", "atomic_schar", "atomic_uchar", "atomic_short", "atomic_ushort", "atomic_int", "atomic_uint", "atomic_long", "atomic_ulong", "atomic_llong", "atomic_ullong", "atomic_char16_t", "atomic_char32_t", "atomic_wchar_t", "atomic_int_least8_t", "atomic_uint_least8_t", "atomic_int_least16_t", "atomic_uint_least16_t", "atomic_int_least32_t", "atomic_uint_least32_t", "atomic_int_least64_t", "atomic_uint_least64_t", "atomic_int_fast8_t", "atomic_uint_fast8_t", "atomic_int_fast16_t", "atomic_uint_fast16_t", "atomic_int_fast32_t", "atomic_uint_fast32_t", "atomic_int_fast64_t", "atomic_uint_fast64_t", "atomic_intptr_t", "atomic_uintptr_t", "atomic_size_t", "atomic_ptrdiff_t", "atomic_intmax_t", "atomic_uintmax_t", ]) gnu_types = frozenset([ "__int128", "signed __int128", "unsigned __int128", ]) cxx17_types = frozenset([ "bool", ]) cosmo_types = frozenset([ "bool32", "int128_t", "int_fast128_t", "int_least128_t", "uint128_t", ]) x86intrin_types = frozenset([ "__m1", "__m2", "__m64", "__m128", "__m128_u", "__m128d", "__m128d_u", "__m128i", "__m128i_u", "__v16qi", "__v16qs", "__v16qu", "__v1di", "__v2df", "__v2di", "__v2du", "__v2sf", "__v2si", "__v4hi", "__v4sf", "__v4si", "__v4su", "__v8hi", "__v8hu", "__v8qi", ]) ################################################################################ kar_kws = frozenset([ "auto", "if", "break", "case", "while", "continue", "default", "return", "do", "signed", "else", "sizeof", "extern", "struct", "switch", "for", "goto", "union", ]) ansi_kws = frozenset([ "auto", "if", "break", "case", "volatile", "while", "const", "register", "continue", "default", "return", "do", "double", "signed", "else", "sizeof", "static", "extern", "struct", "float", "switch", "for", "typedef", "goto", "union", "typedef", "enum", ]) c99_kws= frozenset([ "_Bool", "_Complex", "_Imaginary", "inline", "restrict", ]) c11_kws = frozenset([ "_Alignas", "_Alignof", "_Atomic", "_Generic", "_Noreturn", "_Static_assert", "_Thread_local", ]) cxx17_kws = frozenset([ "alignas", "alignof", "asm", "auto", "bool", "break", "case", "catch", "class", "const", "const_cast", "constexpr", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "mutable", "namespace", "new", "noexcept", "nullptr", "operator", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "using", "virtual", "virtual", "volatile", "volatile", "while", ]) cosmo_kws = frozenset([ "pass", "alignas", "aligned", "alignof", "artificial", "attributeallocalign", "attributeallocsize", "autotype", "byanymeansnecessary", "compatfn", "decltype", "externinline", "firstclass", "flattenout", "forcealignargpointer", "forceinline", "frownedupon", "hasatleast", "_Hide", "initarray", "interruptfn", "mallocesque", "mayalias", "memcpyesque", "nocallback", "nodebuginfo", "dontdiscard", "dontinline", "noinstrument", "nointerpose", "dontoptimize", "noprune", "wontreturn", "nosideeffect", "dontthrow", "null", "nullterminated", "paramsnonnull", "preinitarray", "printfesque", "privileged", "pureconst", "reallocesque", "relegated", "returnsnonnull", "returnspointerwithnoaliases", "returnstwice", "scanfesque", "strftimeesque", "strlenesque", "textexit", "textreal", "textstartup", "textwindows", "thatispacked", "threadlocal", "typeof", "unreachable", "notpossible", "warnifused", "winstruct", "nocallersavedregisters", "pass", "alignas", "aligned", "alignof", "artificial", "attributeallocalign", "attributeallocsize", "autotype", "byanymeansnecessary", "compatfn", "decltype", "externinline", "firstclass", "flattenout", "forcealignargpointer", "forceinline", "frownedupon", "hasatleast", "_Hide", "initarray", "interruptfn", "mallocesque", "mayalias", "memcpyesque", "nocallback", "nodebuginfo", "dontdiscard", "dontinline", "noinstrument", "nointerpose", "dontoptimize", "noprune", "wontreturn", "nosideeffect", "dontthrow", "null", "nullterminated", "paramsnonnull", "preinitarray", "printfesque", "privileged", "pureconst", "reallocesque", "relegated", "returnsnonnull", "returnspointerwithnoaliases", "returnstwice", "scanfesque", "strftimeesque", "strlenesque", "textexit", "textreal", "textstartup", "textwindows", "thatispacked", "threadlocal", "typeof", "unreachable", "notpossible", "warnifused", "winstruct", "nocallersavedregisters", ]) ################################################################################ typegroups = (("kar", kar_types), ("ansi", ansi_types), ("c99", c99_types), ("c11", c11_types), ("gnu", gnu_types), ("cxx17", cxx17_types), ("cosmo", cosmo_types), ("x86intrin", x86intrin_types)) kwgroups = (("kar", kar_kws), ("ansi", ansi_kws), ("c99", c99_kws), ("c11", c11_kws), ("cxx17", cxx17_kws), ("cosmo", cosmo_kws)) types = reduce(lambda a,b: a|b[1], typegroups, set()) kws = reduce(lambda a,b: a|b[1], kwgroups, set()) ################################################################################ for name, gg, nonono in (("cosmo-c-types", typegroups, kws), ("cosmo-c-keywords", kwgroups, types)): first = True sys.stdout.write("""\ (defconst %s-regex (let (""" % name) for k, vs in gg: sys.stdout.write(("""%s(%s (list %s)) """ % ("" if first else "\n ", k, """ """.join('"%s"' % repr(s)[1:][:-1] for s in vs - nonono))).rstrip()) first = False sys.stdout.write(""") (concat "\\<" (regexp-opt (append """) sys.stdout.write(""" """.join(k for k,_ in gg)) sys.stdout.write(""")) "\\>")))\n\n""")
8,185
488
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-stuff.el
;; ╔──────────────────────────────────────────────────────────────────╗ ;; │ To the extent possible under law, Justine Tunney has waived │ ;; │ all copyright and related or neighboring rights to this file, │ ;; │ as it is written in the following disclaimers: │ ;; │ • http://unlicense.org/ │ ;; │ • http://creativecommons.org/publicdomain/zero/1.0/ │ ;; ╚──────────────────────────────────────────────────────────────────╝ ;; Hodgepodge of copypasta from Justine's Emacs config intended to be ;; helpful to those wanting to configure their own Emacs editor to work ;; pretty well as a Cosmopolitan IDE. ;;; Code: (require 'asm-mode) (require 'cc-mode) (require 'fortran) (require 'cosmo-c-types) (require 'cosmo-c-keywords) (require 'cosmo-c-builtins) (require 'cosmo-c-constants) (require 'cosmo-cpp-constants) (require 'cosmo-platform-constants) (require 'dired) (require 'javadown) (require 'ld-script) (require 'make-mode) (setq c-doc-comment-style 'javadown) (add-to-list 'auto-mode-alist '("\\.x$" . c-mode)) ;; -aux-info ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support Macros (defmacro setql (var val) `(set (make-local-variable ',var) ,val)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support Functions (defun cosmo-contains (x s &optional icase) (declare (pure t) (side-effect-free t)) (let ((case-fold-search icase)) (not (null (string-match-p (regexp-quote x) s))))) (defun cosmo-startswith (x s &optional icase) (declare (pure t) (side-effect-free t)) (not (null (string-prefix-p x s icase)))) (defun cosmo-endswith (x s &optional icase) (declare (pure t) (side-effect-free t)) (let ((p (- (length s) (length x)))) (and (>= p 0) (eq t (compare-strings x nil nil s p nil icase))))) (defun cosmo-replace (x y s) (declare (pure t) (side-effect-free t)) (let ((case-fold-search nil)) (replace-regexp-in-string (regexp-quote x) y s t t))) (defun cosmo-join (s l) (declare (pure t) (side-effect-free t)) (mapconcat 'identity l s)) (defun cosmo-lchop (p s) (declare (pure t) (side-effect-free t)) (if (and (>= (length s) (length p)) (string= p (substring s 0 (length p)))) (substring s (length p)) s)) (defun cosmo-first-that (predicate list) (declare (pure t)) (when list (if (funcall predicate (car list)) (car list) (cosmo-first-that predicate (cdr list))))) (defun cosmo-file-name-sans-extensions (filename) (save-match-data (let (directory (file (file-name-sans-versions (file-name-nondirectory filename)))) (if (and (string-match "[.-].*\\'" file) (not (eq 0 (match-beginning 0)))) (if (setq directory (file-name-directory filename)) (concat directory (substring file 0 (match-beginning 0))) (substring file 0 (match-beginning 0))) filename)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; C-c . Jump to symbol definition ;; C-c , Jump back to where we were ;; C-c C-i Show references to symbol ;; TODO(jart): Why doesnt the default-directory variable work? (defun project-current (&optional maybe-prompt dir) (expand-file-name (file-name-directory (locate-dominating-file (buffer-name) "Makefile")))) (defun cosmo-xref-find-references () (interactive) (let ((case-fold-search nil)) (xref-find-references (format "%S" (symbol-at-point))))) (defun cosmo-symbol-at-point (&optional no-properties) (let ((stab (copy-syntax-table))) (with-syntax-table stab (modify-syntax-entry ?+ " ") (modify-syntax-entry ?* " ") (let ((thing (thing-at-point 'symbol no-properties))) (when thing (intern thing)))))) (defun cosmo-xref-find-definitions () (interactive) (let ((case-fold-search nil)) (xref-find-definitions (format "%S" (cosmo-symbol-at-point))))) (global-set-key (kbd "M-,") 'xref-pop-marker-stack) (global-set-key (kbd "M-.") 'cosmo-xref-find-definitions) (global-set-key (kbd "C-c TAB") 'cosmo-xref-find-references) (defun stop-asking-questions-etags () (set (make-local-variable 'tags-file-name) (format "%s/TAGS" (or (locate-dominating-file (buffer-name) "Makefile") (file-name-directory (buffer-name)))))) (add-hook 'c-mode-common-hook 'stop-asking-questions-etags) (add-hook 'c++-mode-common-hook 'stop-asking-questions-etags) (setq tags-revert-without-query t) (setq kill-buffer-query-functions ;; disable kill buffer w/ process question (delq 'process-kill-buffer-query-function kill-buffer-query-functions)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Compile buffer and run associated test and/or display assembly ;; C-c C-c Compile ;; M-1 C-c C-c Compile w/ MODE=tiny ;; M-2 C-c C-c Compile w/ MODE=opt ;; M-3 C-c C-c Compile w/ MODE=rel ;; M-4 C-c C-c Compile w/ MODE=dbg ;; M-5 C-c C-c Compile w/ MODE="" ;; M-7 C-c C-c Compile w/ MODE=aarch64 ;; M-8 C-c C-c Compile w/ MODE=aarch64-tiny ;; M-9 C-c C-c Compile w/ chibicc (defun cosmo-intest (&optional file-name) (let (path root pkg) (and (setq path (or (buffer-file-name) dired-directory)) (setq root (locate-dominating-file path "Makefile")) (setq pkg (file-relative-name path root)) (cosmo-startswith "test/" pkg)))) (defun cosmo--make-mode (arg &optional default) (cond ((eq arg 1) "tiny") ((eq arg 2) "opt") ((eq arg 3) "rel") ((eq arg 4) "dbg") ((eq arg 5) "") ((eq arg 6) "llvm") ((eq arg 7) "aarch64") ((eq arg 8) "aarch64-tiny") (default default) ((cosmo-intest) "dbg") (t "fastbuild"))) (defun cosmo--make-suffix (arg) (cond ((eq arg 9) ".chibicc") (t ""))) (defun cosmo--make-objdump-flags (arg) (cond ((eq arg 9) "-x") (t ""))) (defun cosmo--compile-command (this root kind mode suffix objdumpflags runsuffix) (let* ((ext (file-name-extension this)) ;; e.g. "c" (dir (file-name-directory this)) ;; e.g. "/home/jart/daisy/libc/" (dots (file-relative-name root dir)) ;; e.g. "../" (file (file-relative-name this root)) ;; e.g. "libc/crc32c.c" (name (file-name-sans-extension file)) ;; e.g. "libc/crc32c" (buddy (format "test/%s_test.c" name)) (runs (format "o/$m/%s.com%s V=5 TESTARGS=-b" name runsuffix)) (buns (format "o/$m/test/%s_test.com%s V=5 TESTARGS=-b" name runsuffix))) (cond ((not (member ext '("c" "cc" "s" "S" "rl" "f"))) (format "m=%s; make -j12 MODE=$m o/$m/%s" mode (directory-file-name (or (file-name-directory (file-relative-name this root)) "")))) ((eq kind 'run-win10) (format (cosmo-join " && " `("m=%s; f=o/$m/%s.com" ,(concat "make -j12 $f MODE=$m") "scp $f $f.dbg win10:; ssh win10 ./%s.com")) mode name (file-name-nondirectory name))) ((eq kind 'run-xnu) (format (cosmo-join " && " `("m=%s; f=o/$m/%s.com" ,(concat "make -j12 $f MODE=$m") "scp $f $f.dbg xnu:" "ssh xnu ./%s.com")) mode name (file-name-nondirectory name))) ((and (equal suffix "") (cosmo-contains "_test." (buffer-file-name))) (format "m=%s; make -j12 MODE=$m %s" mode runs)) ((and (equal suffix "") (file-exists-p (format "%s" buddy))) (format (cosmo-join " && " '("m=%s; n=%s; make -j12 o/$m/$n%s.o MODE=$m" ;; "bloat o/$m/%s.o | head" ;; "nm -C --size o/$m/%s.o | sort -r" "echo" "size -A o/$m/$n.o | grep '^[.T]' | grep -v 'debug\\|command.line\\|stack' | sort -rnk2" "build/objdump %s -wzCd o/$m/$n%s.o | c++filt")) mode name suffix objdumpflags suffix)) ((eq kind 'run) (format (cosmo-join " && " `("m=%s; f=o/$m/%s.com" ,(concat "make -j12 $f MODE=$m") "build/run ./$f")) mode name)) ((eq kind 'test) (format `"m=%s; f=o/$m/%s.com.ok && make -j12 $f MODE=$m" mode name)) ((and (file-regular-p this) (file-executable-p this)) (format "build/run ./%s" file)) ('t (format (cosmo-join " && " `("m=%s; f=o/$m/%s%s.o" ,(concat "make -j12 $f MODE=$m") ;; "nm -C --size $f | sort -r" "echo" "size -A $f | grep '^[.T]' | grep -v 'debug\\|command.line\\|stack' | sort -rnk2" "build/objdump %s -wzCd $f | c++filt")) mode name suffix objdumpflags))))) (defun cosmo-compile (arg) (interactive "P") (let* ((this (or (buffer-file-name) dired-directory)) (root (locate-dominating-file this "Makefile"))) (when root (let* ((mode (cosmo--make-mode arg)) (suffix (cosmo--make-suffix arg)) (objdumpflags (cosmo--make-objdump-flags arg)) (compilation-scroll-output nil) (default-directory root) (compile-command (cosmo--compile-command this root nil mode suffix objdumpflags ".runs"))) (compile compile-command))))) (defun cosmo-compile-hook () (local-set-key (kbd "C-c C-c") 'cosmo-compile)) (progn (add-hook 'makefile-mode-hook 'cosmo-compile-hook) (add-hook 'asm-mode-hook 'cosmo-compile-hook) (add-hook 'ld-script-mode-hook 'cosmo-compile-hook) (add-hook 'dired-mode-hook 'cosmo-compile-hook) (add-hook 'c-mode-common-hook 'cosmo-compile-hook) (add-hook 'c++-mode-common-hook 'cosmo-compile-hook) (add-hook 'fortran-mode-hook 'cosmo-compile-hook) (add-hook 'protobuf-mode-hook 'cosmo-compile-hook)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Display assembly for C/C++ buffer ;; ;; C-c C-a Compile and show assembly, with a native optimized build ;; C-c C-b Compile and show assembly, with a balanced build ;; ;; The ALT key may be used to override the default mode. ;; ;; M-1 C-c C-a Compile w/ MODE=tiny ;; M-2 C-c C-a Compile w/ MODE=opt ;; M-3 C-c C-a Compile w/ MODE=rel ;; M-4 C-c C-a Compile w/ MODE=dbg ;; M-5 C-c C-a Compile w/ MODE="" ;; (defvar cosmo--assembly-root nil) (defvar cosmo--assembly-pending nil) (defun cosmo--scrub (regex replace) (replace-regexp regex replace nil (point-min) (point-max))) (defun cosmo--fixup-asm () (cosmo--scrub ;; Code like this ;; ;; .section "GNU!GNU!GNU!.must.be.in.every.asm.or.mprotect.breaks" ;; ;; Isn't needed since the underlying issue is addressed by ape/ape.S ;; which generates executable structure. " .section .note.GNU-stack,.*,@progbits\n" "") (cosmo--scrub ;; Code like this ;; ;; and $2047, %edx ;; ;; Should be this ;; ;; and $2047,%edx ;; ;; Per our favored coding style. ", " ",") (cosmo--scrub ;; Code like this ;; ;; .ascii "foo" ;; .zero 1 ;; ;; Should be this ;; ;; .ascii "foo" ;; .zero 1 ;; ;; @see -frecord-gcc-switches "\t\\.ascii\t\"\\([^\"]*\\)\"\n\t\\.zero\t1\n" "\t.asciz\t\"\\1\"\n") (cosmo--scrub ;; Code like this ;; ;; movl %eax,a ;; movb b,%bl ;; movb $1,c ;; incb d ;; movq %xmm0,%rax ;; ;; Should be this ;; ;; mov %eax,a ;; mov %bl,b ;; movb $1,c ;; incb d ;; movq %xmm0,%rax # ;_; ;; ;; Because we dislike redundancy and don't want the ;; ibmicroborlandtel crowd feeling too uncomfortable. (let ((names-a-register "%[A-Za-z]") (normal-arithmetic-ops (regexp-opt (list "rcr" "rcl" "ror" "rol" "hlt" "cmc" "div" "sar" "mov" "shl" "shr" "lea" "cmp" "adc" "sbb" "inc" "sub" "xor" "add" "and" "or" "not" "btc" "dec" "mul" "neg" "bt" "bsf" "bsr" "int" "test"))) (prefixes (regexp-opt (list "es" "cs" "ss" "ds" "lock" "rep" "repnz" "repne" "repz" "repe" "rex.b" "rex.x" "rex.xb" "rex.r" "rex.rb" "rex.rx" "rex.rxb" "rex.w" "rex.wb" "rex.wx" "rex.wxb" "rex.wr" "rex.trb" "rex.wrx" "rex.wrxb")))) (concat "\\(" "^[ \t]*" "\\(?:" prefixes " \\|\\)" normal-arithmetic-ops "\\)" "[bwlq]" "\\(" "[ \t]+" "\\(?:" "%[A-Wa-w][^\n]+" "\\|" "[^%][^\n,]*,%[A-Za-z][^\n]+" "\\)" "\\)")) "\\1\\2") ;; Scroll first function to top of display. (goto-char (point-min)) (when (search-forward-regexp "\t\\.type[^\n]*@function" nil t) (recenter-top-bottom 'top))) (defun cosmo--assembly-compilation-finished (compilebuf msg) (when cosmo--assembly-pending (let ((asm-gcc (car cosmo--assembly-pending)) (asm-clang (cdr cosmo--assembly-pending)) width asm-gcc-buffer asm-gcc-window asm-clang-buffer asm-clang-window) (setq cosmo--assembly-pending nil) (when (not (cosmo-contains "finished" msg)) (error "making assembly failed: %s" msg)) (let ((f (format "%s/%s" cosmo--assembly-root asm-gcc))) (when (or (null asm-gcc) (not (file-exists-p f))) (error "asm-gcc not found: %s" f))) (let ((f (format "%s/%s" cosmo--assembly-root asm-clang))) (when (or (null asm-gcc) (not (file-exists-p f))) (error "asm-gcc not found: %s" f))) (delete-other-windows) (setq width (window-total-width)) (setq asm-gcc-buffer (find-file-noselect asm-gcc t nil nil)) (setq asm-clang-buffer (find-file-noselect asm-clang t nil nil)) (setq asm-clang-window (split-window-right (- width (/ width 4)))) (setq asm-gcc-window (split-window-right (- (- width (/ width 4)) (/ width 4)))) (set-window-buffer asm-gcc-window asm-gcc-buffer) (set-window-buffer asm-clang-window asm-clang-buffer) (other-window 1) (cosmo--fixup-asm) (save-buffer) (bury-buffer (current-buffer)) (other-window 1) (cosmo--fixup-asm) (save-buffer) (bury-buffer (current-buffer)) (other-window 1) (bury-buffer compilebuf)))) (defun cosmo--purge-file (path) (let ((b (find-file-noselect path t nil nil))) (when b (with-current-buffer b (save-buffer)) (when (not (kill-buffer b)) (error "couldn't kill asm buffer")))) (delete-file path t)) (defun cosmo--assembly (arg extra-make-flags) (let* ((this (expand-file-name (or (buffer-file-name) dired-directory))) (root (expand-file-name (locate-dominating-file this "Makefile")))) (when root (let* ((mode (cosmo--make-mode arg "opt")) (ext (file-name-extension this)) (dir (file-name-directory this)) (dots (file-relative-name root dir)) (file (file-relative-name this root)) (name (file-name-sans-extension file)) (asm-gcc (format "o/%s/%s-gcc.asm" mode name)) (asm-clang (format "o/%s/%s-clang.asm" mode name))) (when (not (member ext '("c" "cc" "f"))) (error "don't know how to show assembly for non c/c++ source file")) (let* ((default-directory root) (compile-command (format "make %s -j12 MODE=%s %s %s" (or extra-make-flags "") mode asm-gcc asm-clang))) (save-buffer) (set-visited-file-modtime (current-time)) (cosmo--purge-file asm-gcc) (cosmo--purge-file asm-clang) (save-buffer) (setq cosmo--assembly-root root) (setq cosmo--assembly-pending (cons asm-gcc asm-clang)) (let ((errormsg (shell-command-to-string (format "touch %s" file)))) (when (not (equal "" errormsg)) (error errormsg))) (revert-buffer :ignore-auto :noconfirm) (compile compile-command)))))) (defun cosmo-assembly (arg) (interactive "P") (setq arg (or arg 2)) ;; -ffast-math -funsafe-math-optimizations -fsched2-use-superblocks -fjump-tables (cond ((eq arg 9) (cosmo--assembly 1 "V=1 OVERRIDE_COPTS='-w -fverbose-asm -fsanitize=undefined -fno-sanitize=null -fno-sanitize=alignment -fno-sanitize=pointer-overflow'")) ;; ((not (eq 0 (logand 8 arg))) ;; (cosmo--assembly (setq arg (logand (lognot 8))) ;; "V=1 OVERRIDE_COPTS='-w -fverbose-asm -fsanitize=address'")) (t (cosmo--assembly arg "V=1 OVERRIDE_COPTS='-w ' CPPFLAGS=''")))) (defun cosmo-assembly-native (arg) (interactive "P") (setq arg (or arg 3)) (cond ((not (eq 0 (logand 8 arg))) (cosmo--assembly (setq arg (logand (lognot 8))) "V=1 CCFLAGS=--verbose COPTS='$(IEEE_MATH)' CPPFLAGS='' TARGET_ARCH='-march=k8'")) ;; znver2 (t (cosmo--assembly arg "V=1 CCFLAGS=--verbose COPTS='$(MATHEMATICAL) -O3' CPPFLAGS='' TARGET_ARCH='-march=k8'")))) ;; znver2 (defun cosmo-assembly-icelake (arg) (interactive "P") (setq arg (or arg 3)) (cond ((not (eq 0 (logand 8 arg))) (cosmo--assembly (setq arg (logand (lognot 8))) "V=1 CCFLAGS=--verbose COPTS='$(MATHEMATICAL) -O3' CPPFLAGS='' TARGET_ARCH='-march=icelake-client'")) (t (cosmo--assembly arg "V=1 CCFLAGS=--verbose COPTS='$(MATHEMATICAL) -O3' CPPFLAGS='' TARGET_ARCH='-march=icelake-client'")))) (defun cosmo-assembly-balanced (arg) (interactive "P") (cosmo--assembly (or arg 5) "CFLAGS='-O2 -ftrapv' CPPFLAGS=''")) (defun cosmo-mca (arg) (interactive "P") (let (code delete cleanup (inhibit-message t) (inhibit-read-only t) (term (getenv "TERM")) (prog (executable-find "llvm-mca-10")) (buf1 (get-buffer-create "*mca*")) (buf2 (generate-new-buffer "*mca*"))) (setenv "TERM" "xterm-256color") (setq cleanup (lambda () (setenv term) (kill-buffer buf2) (when delete (delete-file delete)))) (condition-case exc (progn (if (not (buffer-modified-p)) (setq code (buffer-file-name)) (setq code (make-temp-file "mca.s")) (write-region nil nil code) (setq delete code)) (with-current-buffer buf2 (insert "\n") (setq rc (call-process prog nil t nil "-mcpu=skylake" "-mtriple=x86_64-pc-linux-gnu" "--bottleneck-analysis" "-instruction-info" "-iterations=8" "-all-stats" "-all-views" "-timeline" code))) (with-current-buffer buf1 (replace-buffer-contents buf2) (if (eq rc 0) (fundamental-mode) (compilation-mode)) (xterm-color-colorize-buffer) (display-buffer (current-buffer)))) ('error (funcall cleanup) (error exc))) (funcall cleanup))) (defun cosmo-assemble-hook () (add-to-list 'compilation-finish-functions 'cosmo--assembly-compilation-finished) (local-set-key (kbd "C-c C-a") 'cosmo-assembly) (local-set-key (kbd "C-c C-b") 'cosmo-assembly-balanced) (local-set-key (kbd "C-c C-n") 'cosmo-assembly-native) (local-set-key (kbd "C-c C-i") 'cosmo-assembly-icelake)) (defun cosmo-mca-hook () ;; (local-set-key (kbd "C-c C-h") 'cosmo-mca) ) (progn (add-hook 'asm-mode-hook 'cosmo-mca-hook) (add-hook 'makefile-mode-hook 'cosmo-assemble-hook) (add-hook 'asm-mode-hook 'cosmo-assemble-hook) (add-hook 'ld-script-mode-hook 'cosmo-assemble-hook) (add-hook 'dired-mode-hook 'cosmo-assemble-hook) (add-hook 'c-mode-common-hook 'cosmo-assemble-hook) (add-hook 'fortran-mode-hook 'cosmo-assemble-hook) (add-hook 'protobuf-mode-hook 'cosmo-assemble-hook)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Run buffer. ;; C-c C-r Run ;; M-1 C-c C-r Run w/ MODE=tiny ;; M-2 C-c C-r Run w/ MODE=opt ;; M-3 C-c C-r Run w/ MODE=rel ;; M-4 C-c C-r Run w/ MODE=dbg ;; M-5 C-c C-r Run w/ MODE="" (defun cosmo-run (arg) (interactive "P") (let* ((this (or (buffer-file-name) dired-directory)) (proj (locate-dominating-file this "Makefile")) (root (or proj default-directory)) (file (file-relative-name this root))) (when root (let ((default-directory root)) (save-buffer) (cond ((save-excursion (goto-char (point-min)) (looking-at "#!")) (compile (format "sh -c %s" file))) ((file-executable-p file) (compile (if (cosmo-contains "/" file) file (format "build/run ./%s" file)))) ((memq major-mode '(c-mode c++-mode asm-mode fortran-mode)) (let* ((mode (cosmo--make-mode arg)) (compile-command (cosmo--compile-command this root 'run mode "" "" ".runs"))) (compile compile-command))) ((eq major-mode 'sh-mode) (compile (format "sh -c %s" file))) ((eq major-mode 'lua-mode) (let* ((mode (cosmo--make-mode arg))) (compile (format "make -j16 MODE=%s o/%s/tool/net/redbean.com && build/run o/%s/tool/net/redbean.com -i %s" mode mode mode file)))) ((and (eq major-mode 'python-mode) (cosmo-startswith "third_party/python/Lib/test/" file)) (let ((mode (cosmo--make-mode arg))) (compile (format "make -j12 MODE=%s PYHARNESSARGS=-vv PYTESTARGS=-v o/%s/%s.py.runs" mode mode (file-name-sans-extension file))))) ((eq major-mode 'python-mode) (compile (format "python.com %s" file))) ('t (error "cosmo-run: unknown major mode"))))))) (defun cosmo-run-test (arg) (interactive "P") (let* ((this (or (buffer-file-name) dired-directory)) (proj (locate-dominating-file this "Makefile")) (root (or proj default-directory)) (file (file-relative-name this root))) (when root (let ((default-directory root)) (save-buffer) (cond ((memq major-mode '(c-mode c++-mode asm-mode fortran-mode)) (let* ((mode (cosmo--make-mode arg "fastbuild")) (compile-command (cosmo--compile-command this root 'test mode "" "" ".ok"))) (compile compile-command))) ('t (error "cosmo-run: unknown major mode"))))))) (defun cosmo-run-win10 (arg) (interactive "P") (let* ((this (or (buffer-file-name) dired-directory)) (proj (locate-dominating-file this "Makefile")) (root (or proj default-directory)) (file (file-relative-name this root))) (when root (let ((default-directory root)) (save-buffer) (cond ((memq major-mode '(c-mode c++-mode asm-mode fortran-mode)) (let* ((mode (cosmo--make-mode arg "fastbuild")) (compile-command (cosmo--compile-command this root 'run-win10 mode "" "" ""))) (compile compile-command))) ('t (error "cosmo-run: unknown major mode"))))))) (progn (define-key asm-mode-map (kbd "C-c C-r") 'cosmo-run) (define-key c-mode-base-map (kbd "C-c C-r") 'cosmo-run) (define-key fortran-mode-map (kbd "C-c C-r") 'cosmo-run) (define-key sh-mode-map (kbd "C-c C-r") 'cosmo-run) (define-key lua-mode-map (kbd "C-c C-r") 'cosmo-run) (define-key python-mode-map (kbd "C-c C-r") 'cosmo-run) (define-key c-mode-map (kbd "C-c C-s") 'cosmo-run-test) (define-key c-mode-map (kbd "C-c C-_") 'cosmo-run-win7) (define-key c-mode-map (kbd "C-c C-_") 'cosmo-run-win10)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Debug buffer. ;; C-c C-d Run in GDB/GUD ;; M-1 C-c C-d Run in GDB/GUD w/ MODE=tiny ;; M-2 C-c C-d Run in GDB/GUD w/ MODE=opt ;; M-3 C-c C-d Run in GDB/GUD w/ MODE=rel ;; M-4 C-c C-d Run in GDB/GUD w/ MODE=dbg ;; M-5 C-c C-d Run in GDB/GUD w/ MODE="" (defun cosmo-debug (arg) (interactive "P") (let* ((this (or (buffer-file-name) dired-directory)) (root (locate-dominating-file this "Makefile"))) (when root (let* ((mode (cosmo--make-mode arg "dbg")) (name (file-relative-name this root)) (next (file-name-sans-extension name)) (exec (format "o/%s/%s.com.dbg" mode next)) (default-directory root) (compile-command (cosmo--compile-command this root nil mode "" "" ".runs"))) (compile compile-command) (gdb (format "gdb -q -nh -i=mi %s -ex run" exec)))))) (progn (define-key asm-mode-map (kbd "C-c C-d") 'cosmo-debug) (define-key c-mode-base-map (kbd "C-c C-d") 'cosmo-debug)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; C-c C-t Toggle buffer between source file and unit test file. (defun cosmo-toggle-buddy () (interactive) (let* ((this (or (buffer-file-name) dired-directory)) (root (locate-dominating-file this "Makefile"))) (when root (let* ((name (file-relative-name this root)) (dir (file-name-directory this)) (pkgname (file-name-nondirectory (substring dir 0 -1))) (dots (file-relative-name root dir)) (notest (cosmo-file-name-sans-extensions (cosmo-replace "_test" "" (cosmo-lchop "test/" name)))) (buddy (cond ((and (cosmo-startswith "test/" dir) (cosmo-endswith "/test.mk" name)) (message (format "%s/%s.mk" (substring dir 5) pkgname)) (format "%s/%s.mk" (substring dir 5) pkgname)) ((cosmo-startswith "test/" name) (cosmo-first-that 'file-exists-p (list (concat dots notest ".s") (concat dots notest ".S") (concat dots notest ".f") (concat dots notest ".F") (concat dots notest ".c") (concat dots notest ".cc") (concat dots notest ".rl") (concat dots notest ".greg.c") (concat dots notest ".ncabi.c") (concat dots notest ".hookabi.c") (concat dots notest ".h")))) (t (format "%stest/%s_test.c" dots (cosmo-file-name-sans-extensions name)))))) (when buddy (find-file buddy)))))) (progn (global-set-key (kbd "C-c C-t") 'cosmo-toggle-buddy)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; C-c C-h Add Include Line (defun cosmo-add-include () (interactive) (let* ((no-whine t) (tag-file "HTAGS") (this (buffer-name)) (case-fold-search nil) (search (thing-at-point 'symbol)) (buffer (find-file-noselect (format "%s/%s" (locate-dominating-file this tag-file) tag-file) no-whine)) (header (with-current-buffer buffer (revert-buffer :ignore-auto :noconfirm) (save-excursion (goto-char 0) (when (re-search-forward (concat "\177" search "\001") nil t) (when (re-search-backward "\f\n\\([^,]*\\)," nil t) (match-string 1)))))) (root (locate-dominating-file this "Makefile")) (name (file-relative-name this root))) (when header (when (not (equal header name)) (save-excursion (goto-char 0) (re-search-forward "#include" nil t) (re-search-forward "^$") (re-search-backward "#include" nil t) (beginning-of-line) (insert (concat "#include \"" header "\"\n")))) (message header)))) (progn (define-key prog-mode-map (kbd "C-c C-h") 'cosmo-add-include) (define-key asm-mode-map (kbd "C-c C-h") 'cosmo-add-include) (define-key c-mode-base-map (kbd "C-c C-h") 'cosmo-add-include) (define-key c++-mode-map (kbd "C-c C-h") 'cosmo-add-include)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; C-c C-o Show Optimization Report (defun cosmo-show-optinfo (arg) (interactive "P") (let* ((mode (cosmo--make-mode arg "opt")) (this (or (buffer-file-name) dired-directory)) (root (locate-dominating-file this "Makefile"))) (when root (let* ((name (file-relative-name this root)) (buddy (format "%s/o/%s/%s.optinfo.gz" root mode (cosmo-file-name-sans-extensions name)))) (when buddy (find-file buddy)))))) (defun cosmo-lisp-is-the-best () (define-key c-mode-base-map (kbd "C-c C-o") 'cosmo-show-optinfo)) (add-hook 'c-mode-common-hook 'cosmo-lisp-is-the-best) (defun cosmo-lisp-is-the-best++ () (define-key c++-mode-base-map (kbd "C-c C-o") 'cosmo-show-optinfo)) (add-hook 'c++-mode-common-hook 'cosmo-lisp-is-the-best++) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Cosmopolitan Extended Language Keyword Definitions (defun cosmo-c-keywords-hook () (font-lock-add-keywords nil `((,cosmo-c-keywords-regex . font-lock-keyword-face) (,cosmo-c-builtins-regex . font-lock-builtin-face) (,cosmo-platform-constants-regex . font-lock-builtin-face) (,cosmo-cpp-constants-regex . font-lock-constant-face) (,cosmo-c-constants-regex . font-lock-constant-face) (,cosmo-c-types-regex . font-lock-type-face)))) (defun cosmo-asm-keywords-hook () (font-lock-add-keywords nil `((,cosmo-cpp-constants-regex . font-lock-constant-face) (,cosmo-platform-constants-regex . font-lock-constant-face)))) (add-hook 'c-mode-common-hook 'cosmo-c-keywords-hook) (add-hook 'c++-mode-common-hook 'cosmo-c-keywords-hook) (add-hook 'asm-mode-hook 'cosmo-asm-keywords-hook) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Symbol naming convention conversion ;; e.g. STARTF_USESHOWWINDOW -> kNtStartfUseshowwindow (defun cosmo--ms-to-google-const (s) (declare (pure t) (side-effect-free t)) (let ((d (downcase (substring s 1)))) (cosmo-replace "kNtNt" "kNt" (concat "kNt" (substring s 0 1) (replace-regexp-in-string "_\\([A-Za-z]\\)" (lambda (m) (upcase (match-string 1 m))) d))))) ;; e.g. kNtStartfUseshowwindow -> STARTF_USESHOWWINDOW (defun cosmo--google-to-ms-const (s) (declare (pure t) (side-effect-free t)) (upcase (replace-regexp-in-string "\\(.\\)\\([A-Z]\\)" (lambda (m) (upcase (concat (match-string 1 m) "_" (match-string 2 m)))) (substring s 3) t))) (defun cosmo-toggle-ms-const () (interactive) (let* ((case-fold-search nil) (bounds (if (use-region-p) (cons (region-beginning) (region-end)) (bounds-of-thing-at-point 'symbol))) (text (buffer-substring-no-properties (car bounds) (cdr bounds)))) (when bounds (let ((fn (if (or (cosmo-contains "_" text) (equal text (upcase text))) 'cosmo--ms-to-google-const 'cosmo--google-to-ms-const))) (delete-region (car bounds) (cdr bounds)) (insert (funcall fn text)))))) ;; (define-key c-mode-base-map (kbd "C-c C-l") 'cosmo-toggle-ms-const) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CP/M EOF for the lulz (defun cosmo-before-save () (cond ((memq major-mode '(c-mode asm-mode)) (set (make-local-variable 'require-final-newline) (not (equal (buffer-substring-no-properties (- (point-max) 1) (point-max)) "\x1a")))))) (add-hook 'before-save-hook 'cosmo-before-save) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Cosmopolitan Logger Integration ;; Cosmopolitan logger ;; ;; W2022-03-23T15:58:19.102930:tool/build/runit.c:274:runit:20719] hello ;; warn date time micros file line prog pid message ;; ;; I2022-03-23T15:58:19.+00033:tool/build/runit.c:274:runit:20719] there ;; info date time delta file line prog pid message ;; (defvar cosmo-compilation-regexps (list (cosmo-join "" '("^[FEWIVDNT]" ;; level "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" ;; date "T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" ;; time "[+.][0-9][0-9][0-9][0-9][0-9][0-9]" ;; micros ":\\([^:]+\\)" ;; file ":\\([0-9]+\\)")) ;; line 1 2)) (eval-after-load 'compile '(progn (add-to-list 'compilation-error-regexp-alist-alist (cons 'cosmo cosmo-compilation-regexps)) (add-to-list 'compilation-error-regexp-alist 'cosmo))) (provide 'cosmo-stuff) ;;; cosmo-stuff.el ends here
35,151
927
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-cpp-constants.el
(defconst cosmo-cpp-constants-c11 '("__STDC_IEC_559__" "__FILE__" "__LINE__" "__DATE__")) (defconst cosmo-cpp-constants-chibicc '("__cosmo__" "__chibicc__")) (defconst cosmo-cpp-constants-gcc-412 '("__BASE_FILE__" "__CHAR_BIT__" "__FUNCTION__" "__GNUC_MINOR__" "__GNUC_PATCHLEVEL__" "__GNUC__" "__APPLE__" "__HAIKU__" "__CYGWIN__" "__EMSCRIPTEN__" "__ANDROID__" "__FreeBSD__" "__NetBSD__" "__NetBSD_Version__" "__OpenBSD__" "__COSMOPOLITAN__" "__GLIBC__" "__linux" "__MACH__" "__GNUG__" "__INCLUDE_LEVEL__" "__INTMAX_MAX__" "__INT_MAX__" "__LONG_LONG_MAX__" "__LONG_MAX__" "__SCHAR_MAX__" "__SHRT_MAX__" "__DBL_MIN__" "__DBL_MAX__" "__LDBL_MIN__" "__LDBL_MAX__" "__FLT_MIN__" "__FLT_MAX__" "__WCHAR_MAX__" "__WCHAR_UNSIGNED__" "__AES__" "__AVX__" "__AVX2__" "__AVX512F__" "__AVXVNNI__" "__ABM__" "__BMI__" "__BMI2__" "__FMA__" "__FAST_MATH__" "__FMA4__" "__F16C__" "__CLZERO__" "__MWAITX__" "__SGX__" "__VAES__" "__VSX__" "__ADX__" "__PCLMUL__" "__POPCNT__" "__RDRND__" "__RDSEED__" "__SHA__" "__SSE__" "__SSE2__" "__SSE3__" "__SSSE3__" "__SSE4_1__" "__SSE4_2__" "__XSAVE__" "__CLFLUSHOPT__" "__RDPID__" "FLT_ROUNDS")) (defconst cosmo-cpp-constants-gcc-92 '("__x86_64__" "__arm__" "__aarch64__" "__AARCH64EB__" "__ARM_NEON" "__powerpc__" "__powerpc64__" "__POWER9_VECTOR__" "__wasm_simd128__" "_ARCH_PWR5X" "__mips__" "__s390__" "__s390x__" "__mips64" "__m68k__" "__riscv" "__riscv_flen" "__riscv_xlen" "__MICROBLAZE__" "__amd64__" "__WINT_MAX__" "__BIGGEST_ALIGNMENT__" "__SIZE_MAX__" "__PTRDIFF_MAX__" "__UINTMAX_MAX__" "__SIG_ATOMIC_MAX__" "__INT8_MAX__" "__INT16_MAX__" "__INT32_MAX__" "__INT64_MAX__" "__UINT8_MAX__" "__UINT16_MAX__" "__UINT32_MAX__" "__UINT64_MAX__" "__INT_LEAST8_MAX__" "__INT_LEAST16_MAX__" "__INT_LEAST32_MAX__" "__INT_LEAST64_MAX__" "__UINT_LEAST8_MAX__" "__UINT_LEAST16_MAX__" "__UINT_LEAST32_MAX__" "__UINT_LEAST64_MAX__" "__INT_FAST8_MAX__" "__INT_FAST16_MAX__" "__INT_FAST32_MAX__" "__INT_FAST64_MAX__" "__UINT_FAST8_MAX__" "__UINT_FAST16_MAX__" "__UINT_FAST32_MAX__" "__UINT_FAST64_MAX__" "__INTPTR_MAX__" "__UINTPTR_MAX__" "__WCHAR_MIN__" "__WINT_MIN__" "__SIG_ATOMIC_MIN__" "__SCHAR_WIDTH__" "__SHRT_WIDTH__" "__INT_WIDTH__" "__LONG_WIDTH__" "__LONG_LONG_WIDTH__" "__PTRDIFF_WIDTH__" "__SIG_ATOMIC_WIDTH__" "__SIZE_WIDTH__" "__WCHAR_WIDTH__" "__WINT_WIDTH__" "__INT_LEAST8_WIDTH__" "__INT_LEAST16_WIDTH__" "__INT_LEAST32_WIDTH__" "__INT_LEAST64_WIDTH__" "__INT_FAST8_WIDTH__" "__INT_FAST16_WIDTH__" "__INT_FAST32_WIDTH__" "__INT_FAST64_WIDTH__" "__INTPTR_WIDTH__" "__INTMAX_WIDTH__" "__SIZEOF_INT__" "__SIZEOF_INTMAX__" "__SIZEOF_UINTMAX__" "__SIZEOF_LONG__" "__SIZEOF_LONG_LONG__" "__SIZEOF_SHORT__" "__SIZEOF_POINTER__" "__SIZEOF_FLOAT__" "__SIZEOF_DOUBLE__" "__SIZEOF_LONG_DOUBLE__" "__SIZEOF_SIZE_T__" "__SIZEOF_WCHAR_T__" "__SIZEOF_WINT_T__" "__SIZEOF_PTRDIFF_T__" "__TIMESTAMP__" "_GNU_SOURCE" "_BSD_SOURCE" "_XOPEN_SOURCE")) (defconst cosmo-cpp-constants-cosmopolitan '("__SAUCE__" "PAGESIZE" "GUARDSIZE" "FRAMESIZE" "BIGPAGESIZE" "STACKSIZE" "ARG_MAX" "PATH_MAX" "BUFSIZ" "CACHELINE" "CHAR_BIT" "NAME_MAX" "NSIG" "CHILD_MAX" "OPEN_MAX" "ATEXIT_MAX" "LONG_BIT" "IM_FEELING_NAUGHTY" "__REAL_MODE__" "__ia16__" "__x86__" "__i386__" "__i486__" "__i586__" "__i686__" "__W__" "__PG__" "__MFENTRY__" "__MNO_VZEROUPPER__" "__MNO_RED_ZONE__" "__MNOP_MCOUNT__" "__MRECORD_MCOUNT__" "__FNO_OMIT_FRAME_POINTER__")) (defconst cosmo-cpp-constants-clang '("__llvm__" "__clang__" "_MSC_VER" "_WIN32" "__MINGW32__" "__INTEL_COMPILER")) (defconst cosmo-cpp-constants (append cosmo-cpp-constants-c11 cosmo-cpp-constants-clang cosmo-cpp-constants-gcc-92 cosmo-cpp-constants-gcc-412 cosmo-cpp-constants-chibicc cosmo-cpp-constants-cosmopolitan)) (defconst cosmo-cpp-constants-regex (concat "\\_<" (regexp-opt cosmo-cpp-constants) "\\_>")) (provide 'cosmo-cpp-constants)
4,628
231
jart/cosmopolitan
false
cosmopolitan/tool/emacs/protobuf-mode.el
;;; protobuf-mode.el --- major mode for editing protocol buffers. ;; Author: Alexandre Vassalotti <[email protected]> ;; Created: 23-Apr-2009 ;; Version: 0.3 ;; Package-Version: 3.10.0 ;; Keywords: google protobuf languages ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are ;; met: ;; ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above ;; copyright notice, this list of conditions and the following disclaimer ;; in the documentation and/or other materials provided with the ;; distribution. ;; * Neither the name of Google Inc. nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; Commentary: ;; Installation: ;; - Put `protobuf-mode.el' in your Emacs load-path. ;; - Add this line to your .emacs file: ;; (require 'protobuf-mode) ;; ;; You can customize this mode just like any mode derived from CC Mode. If ;; you want to add customizations specific to protobuf-mode, you can use the ;; `protobuf-mode-hook'. For example, the following would make protocol-mode ;; use 2-space indentation: ;; ;; (defconst my-protobuf-style ;; '((c-basic-offset . 2) ;; (indent-tabs-mode . nil))) ;; ;; (add-hook 'protobuf-mode-hook ;; (lambda () (c-add-style "my-style" my-protobuf-style t))) ;; ;; Refer to the documentation of CC Mode for more information about ;; customization details and how to use this mode. ;; ;; TODO: ;; - Make highlighting for enum values work properly. ;; - Fix the parser to recognize extensions as identifiers and not ;; as casts. ;; - Improve the parsing of option assignment lists. For example: ;; optional int32 foo = 1 [(my_field_option) = 4.5]; ;; - Add support for fully-qualified identifiers (e.g., with a leading "."). ;;; Code: (require 'cc-mode) (eval-when-compile (and (= emacs-major-version 24) (>= emacs-minor-version 4) (require 'cl)) (require 'cc-langs) (require 'cc-fonts)) ;; This mode does not inherit properties from other modes. So, we do not use ;; the usual `c-add-language' function. (eval-and-compile (put 'protobuf-mode 'c-mode-prefix "protobuf-")) ;; The following code uses of the `c-lang-defconst' macro define syntactic ;; features of protocol buffer language. Refer to the documentation in the ;; cc-langs.el file for information about the meaning of the -kwds variables. (c-lang-defconst c-primitive-type-kwds protobuf '("double" "float" "int32" "int64" "uint32" "uint64" "sint32" "sint64" "fixed32" "fixed64" "sfixed32" "sfixed64" "bool" "string" "bytes" "group")) (c-lang-defconst c-modifier-kwds protobuf '("required" "optional" "repeated")) (c-lang-defconst c-class-decl-kwds protobuf '("message" "enum" "service")) (c-lang-defconst c-constant-kwds protobuf '("true" "false")) (c-lang-defconst c-other-decl-kwds protobuf '("package" "import")) (c-lang-defconst c-other-kwds protobuf '("default" "max")) (c-lang-defconst c-identifier-ops ;; Handle extended identifiers like google.protobuf.MessageOptions protobuf '((left-assoc "."))) ;; The following keywords do not fit well in keyword classes defined by ;; cc-mode. So, we approximate as best we can. (c-lang-defconst c-type-list-kwds protobuf '("extensions" "to" "reserved")) (c-lang-defconst c-typeless-decl-kwds protobuf '("extend" "rpc" "option" "returns")) ;; Here we remove default syntax for loops, if-statements and other C ;; syntactic features that are not supported by the protocol buffer language. (c-lang-defconst c-brace-list-decl-kwds ;; Remove syntax for C-style enumerations. protobuf nil) (c-lang-defconst c-block-stmt-1-kwds ;; Remove syntax for "do" and "else" keywords. protobuf nil) (c-lang-defconst c-block-stmt-2-kwds ;; Remove syntax for "for", "if", "switch" and "while" keywords. protobuf nil) (c-lang-defconst c-simple-stmt-kwds ;; Remove syntax for "break", "continue", "goto" and "return" keywords. protobuf nil) (c-lang-defconst c-paren-stmt-kwds ;; Remove special case for the "(;;)" in for-loops. protobuf nil) (c-lang-defconst c-label-kwds ;; Remove case label syntax for the "case" and "default" keywords. protobuf nil) (c-lang-defconst c-before-label-kwds ;; Remove special case for the label in a goto statement. protobuf nil) (c-lang-defconst c-cpp-matchers ;; Disable all the C preprocessor syntax. protobuf nil) (c-lang-defconst c-decl-prefix-re ;; Same as for C, except it does not match "(". This is needed for disabling ;; the syntax for casts. protobuf "\\([\{\};,]+\\)") ;; Add support for variable levels of syntax highlighting. (defconst protobuf-font-lock-keywords-1 (c-lang-const c-matchers-1 protobuf) "Minimal highlighting for protobuf-mode.") (defconst protobuf-font-lock-keywords-2 (c-lang-const c-matchers-2 protobuf) "Fast normal highlighting for protobuf-mode.") (defconst protobuf-font-lock-keywords-3 (c-lang-const c-matchers-3 protobuf) "Accurate normal highlighting for protobuf-mode.") (defvar protobuf-font-lock-keywords protobuf-font-lock-keywords-3 "Default expressions to highlight in protobuf-mode.") ;; Our syntax table is auto-generated from the keyword classes we defined ;; previously with the `c-lang-const' macro. (defvar protobuf-mode-syntax-table nil "Syntax table used in protobuf-mode buffers.") (or protobuf-mode-syntax-table (setq protobuf-mode-syntax-table (funcall (c-lang-const c-make-mode-syntax-table protobuf)))) (defvar protobuf-mode-abbrev-table nil "Abbreviation table used in protobuf-mode buffers.") (defvar protobuf-mode-map nil "Keymap used in protobuf-mode buffers.") (or protobuf-mode-map (setq protobuf-mode-map (c-make-inherited-keymap))) (easy-menu-define protobuf-menu protobuf-mode-map "Protocol Buffers Mode Commands" (cons "Protocol Buffers" (c-lang-const c-mode-menu protobuf))) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.proto\\'" . protobuf-mode)) ;;;###autoload (defun protobuf-mode () "Major mode for editing Protocol Buffers description language. The hook `c-mode-common-hook' is run with no argument at mode initialization, then `protobuf-mode-hook'. Key bindings: \\{protobuf-mode-map}" (interactive) (kill-all-local-variables) (set-syntax-table protobuf-mode-syntax-table) (setq major-mode 'protobuf-mode mode-name "Protocol-Buffers" local-abbrev-table protobuf-mode-abbrev-table abbrev-mode t) (use-local-map protobuf-mode-map) (c-initialize-cc-mode t) (if (fboundp 'c-make-emacs-variables-local) (c-make-emacs-variables-local)) (c-init-language-vars protobuf-mode) (c-common-init 'protobuf-mode) (easy-menu-add protobuf-menu) (c-run-mode-hooks 'c-mode-common-hook 'protobuf-mode-hook) (c-update-modeline)) (provide 'protobuf-mode) ;;; protobuf-mode.el ends here
7,925
225
jart/cosmopolitan
false
cosmopolitan/tool/emacs/javadown.el
;;; javadown.el --- C/C++ Markdown Javadocs ;; Copyright 2019 Justine Tunney ;; Author: Justine Tunney ;; Version: 0.1 ;; 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. ;;; Commentary: ;; ;; Unintentionally empty. ;;; Code: (require 'cc-fonts) (defconst javadown-font-lock-doc-comments `(;; e.g. ### Implementation Details ("^\\(/\\*\\)?\\(\\s \\|\\*\\)*\\(#+[^\n\r]+\\)" 3 ,c-doc-markup-face-name prepend nil) ;; e.g. {@code param} ("{@[a-z]+[^}\n\r]*}" 0 ,c-doc-markup-face-name prepend nil) ;; e.g. @param name does stuff ("^\\(/\\*\\)?\\(\\s \\|\\*\\)*\\(@[a-z]+\\)" 3 ,c-doc-markup-face-name prepend nil) ;; e.g. <video src=doge.mp4> (,(concat "</?\\sw" "\\(" (concat "\\sw\\|\\s \\|[=\n\r*.:]\\|" "\"[^\"]*\"\\|'[^']*'") "\\)*>") 0 ,c-doc-markup-face-name prepend nil))) ;; (defconst javadown-font-lock-doc-comments ;; `(("{@[a-z]+[^}\n\r]*}" ; "{@foo ...}" markup. ;; 0 ,c-doc-markup-face-name prepend nil) ;; ("^\\(/\\*\\)?\\(\\s \\|\\*\\)*\\(@[a-z]+\\)" ; "@foo ..." markup. ;; 3 ,c-doc-markup-face-name prepend nil) ;; (,(concat "</?\\sw" ; HTML tags. ;; "\\(" ;; (concat "\\sw\\|\\s \\|[=\n\r*.:]\\|" ;; "\"[^\"]*\"\\|'[^']*'") ;; "\\)*>") ;; 0 ,c-doc-markup-face-name prepend nil) ;; ;; ("&\\(\\sw\\|[.:]\\)+;" ; HTML entities. ;; ;; 0 ,c-doc-markup-face-name prepend nil) ;; ;; Fontify remaining markup characters as invalid. Note ;; ;; that the Javadoc spec is hazy about when "@" is ;; ;; allowed in non-markup use. [jart: we like markdown] ;; ;; (,(lambda (limit) ;; ;; (c-find-invalid-doc-markup "[<>&]\\|{@" limit)) ;; ;; 0 'font-lock-warning-face prepend nil) ;; )) (defconst javadown-font-lock-keywords `((,(lambda (limit) (c-font-lock-doc-comments "/\\*\\*" limit javadown-font-lock-doc-comments))))) (provide 'javadown) ;;; javadown.el ends here
2,679
75
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-c-keywords.el
(defconst cosmo-c-keywords-regex (let ( (c99 '("inline" "restrict" "_Imaginary" "_Bool" "_Pragma" "_Complex")) (c11 '("_Atomic" "alignas" "_Alignas" "alignof" "_Alignof" "_Noreturn" "_Generic" "thread_local" "_Thread_local" "static_assert" "_Static_assert" "_Complex_I" "_Imaginary_I")) (cosmo '("__msabi" "__funline" "function" "offsetof" "microarchitecture" "targetclones" "forcealignargpointer" "textexit" "externinline" "dontinline" "dontclone" "donothing" "notsan" "printfesque" "flattenout" "mallocesque" "vallocesque" "null" "paramsnonnull" "returnspointerwithnoaliases" "alignas" "nosideeffect" "decltype" "forceinline" "nocallersavedregisters" "dontthrow" "dontoptimize" "optimizesize" "optimizespeed" "alignof" "relegated" "antiquity" "memcpyesque" "libcesque" "artificial" "returnstwice" "returnsaligned" "noprune" "reallocesque" "nullterminated" "unreachable" "notpossible" "_Hide" "privileged" "hasatleast" "nodebuginfo" "frownedupon" "wontreturn" "noasan" "nomsan" "noubsan" "nostackprotector" "initarray" "mayalias" "noinstrument" "interruptfn" "nocallback" "textstartup" "warnifused" "attributeallocsize" "attributeallocalign" "dontdiscard" "nointerpose" "compatfn" "returnsnonnull" "strftimeesque" "firstclass" "preinitarray" "scanfesque" "pureconst" "thatispacked" "strlenesque" "textwindows" "forcealign" "typeof" "textreal" "texthead" "autotype" "_Section" "_Vector_size")) (gnu '("__extension__" "__inline" "__thread" "__alignof" "__typeof" "__restrict" "__const__" "__label__" "__noinline__" "__noclone__" "__force_align_arg_pointer__" "__always_inline__" "__gnu_inline__" "__alignof__" "__asm__" "__attribute__" "__auto_type" "__byte__" "__complex__" "__imag__" "__may_alias__" "__noreturn__" "__packed__" "__pointer__" "__printf__" "__real__" "__restrict__" "__scanf__" "__strfmon__" "__strftime__" "__strong__" "__target__" "__transparent_union__" "__typeof__" "__volatile__" "__word__" "__alias__" "__aligned__" "__alloc_align__" "__alloc_size__" "__warn_if_not_aligned__" "__artificial__" "__assume_aligned__" "__cold__" "__constructor__" "__destructor__" "__copy__" "__deprecated__" "__error__" "__warning__" "__externally_visible__" "__flatten__" "__format__" "__gnu_format__" "__gnu_printf__" "__gnu_scanf__" "__format_arg__" "__hot__" "__ifunc__" "__interrupt__" "__interrupt_handler__" "__leaf__" "__no_caller_saved_registers__" "__malloc__" "__no_icf__" "__no_instrument_function__" "__no_profile_instrument_function__" "__no_reorder__" "__no_sanitize__" "__no_sanitize_address__" "__no_address_safety_analysis__" "__no_sanitize_thread__" "__no_stack_protector__" "__leaf__" "__no_sanitize_undefined__" "__no_split_stack__" "__no_stack_limit__" "__noclone__" "__noipa__" "__nonnull__" "__noplt__" "__nothrow__" "__optimize__" "__pure__" "__patchable_function_entry__" "__returns_nonnull__" "__returns_twice__" "__section__" "__sentinel__" "__simd__" "__target_clones__" "__unused__" "__used__" "__visibility__" "__warn_unused_result__" "__params_nonnull__" "__weak__" "__vector_size__" "__ms_abi__" "__sysv_abi__" "systemfive" "__mode__" "__seg_fs" "__seg_gs")) (clang '("__optnone__" "__nodebug__" "musttail" "__musttail__")) ) (concat "\\_<" (regexp-opt (append c11 gnu clang cosmo)) "\\_>"))) (provide 'cosmo-c-keywords)
5,709
231
jart/cosmopolitan
false
cosmopolitan/tool/emacs/c.lang
-- C Language Definition for Unix `highlight` Command, e.g. -- sudo cp tool/emacs/c.lang /usr/share/highlight/langDefs/ -- { printf '<!doctype html>\n<meta charset="utf-8">\n'; highlight -Ohtml --encoding=utf-8 --class-name=NONE --src-lang=c tool/viz/life.c; } >life.c.html -- .num { color: #000000; } /* number */ -- .esc { color: #80216b; } /* escape sequence */ -- .ipl { color: #008080; } /* string interpolation */ -- .str { color: #5a5127; } /* string */ -- .ppc { color: #685809; } /* preprocessor */ -- .pps { color: #273122; } /* preprocessor string */ -- .com { color: #0e6729; } /* multiline comment */ -- .slc { color: #0e6729; } /* single line comment */ -- .lin { color: #75715e; } /* wut */ -- .opt { color: #000000; } /* operator */ -- .kwa { color: #5332d8; } /* keyword */ -- .kwb { color: #8c1a94; } /* type */ -- .kwc { color: #6b2c75; } /* builtin */ -- .kwd { color: #9609a7; } /* constant */ Description="C" Categories = {"source"} Digits = [[ (?:0x|0X|0b)[0-9a-fA-F']+|\d*[\.]?\d+(?:[eE][\-\+]\d+)?[lLuU]* ]] Keywords={ { Id=1, List={ "case", "do", "return", "struct", "for", "default", "auto", "while", "else", "break", "union", "switch", "continue", "extern", "sizeof", "if", "goto", "static", "sizeof", "if", "typedef", "const", "struct", "for", "union", "switch", "volatile", "do", "return", "goto", "auto", "enum", "else", "break", "extern", "case", "default", "register", "while", "continue", "inline", "restrict", "_Imaginary", "_Bool", "_Pragma", "_Complex", "_Atomic", "_Alignas", "_Alignof", "_Noreturn", "_Generic", "_Thread_local", "_Static_assert", "_Complex_I", "_Imaginary_I", "__inline", "__msabi", "offsetof", "microarchitecture", "targetclones", "forcealignargpointer", "textexit", "externinline", "dontinline", "dontclone", "donothing", "printfesque", "flattenout", "mallocesque", "vallocesque", "paramsnonnull", "returnspointerwithnoaliases", "alignas", "nosideeffect", "decltype", "forceinline", "nocallersavedregisters", "dontthrow", "dontoptimize", "optimizesize", "optimizespeed", "alignof", "relegated", "memcpyesque", "libcesque", "artificial", "returnstwice", "returnsaligned", "noprune", "reallocesque", "nullterminated", "unreachable", "notpossible", "_Hide", "privileged", "hasatleast", "nodebuginfo", "frownedupon", "noreturn", "initarray", "mayalias", "noinstrument", "interruptfn", "nocallback", "textstartup", "warnifused", "attributeallocsize", "attributeallocalign", "dontdiscard", "nointerpose", "compatfn", "returnsnonnull", "strftimeesque", "firstclass", "preinitarray", "scanfesque", "pureconst", "thatispacked", "strlenesque", "textwindows", "aligned", "typeof", "textreal", "autotype", "_Section", "_Vector_size", "__thread", "__alignof", "__typeof", "__restrict", "__const__", "__label__", "__noinline__", "__noclone__", "__force_align_arg_pointer__", "__always_inline__", "__gnu_inline__", "__alignof__", "__asm__", "__attribute__", "__auto_type", "__byte__", "__complex__", "__imag__", "__may_alias__", "__noreturn__", "__packed__", "__pointer__", "__printf__", "__real__", "__restrict__", "__scanf__", "__strfmon__", "__strftime__", "__strong__", "__target__", "__transparent_union__", "__typeof__", "__volatile__", "__word__", "__alias__", "__aligned__", "__alloc_align__", "__alloc_size__", "__artificial__", "__assume_aligned__", "__cold__", "__constructor__", "__destructor__", "__copy__", "__deprecated__", "__error__", "__warning__", "__externally_visible__", "__flatten__", "__format__", "__gnu_format__", "__gnu_printf__", "__gnu_scanf__", "__format_arg__", "__hot__", "__ifunc__", "__interrupt__", "__interrupt_handler__", "__leaf__", "__no_caller_saved_registers__", "__malloc__", "__no_icf__", "__no_instrument_function__", "__no_profile_instrument_function__", "__no_reorder__", "__no_sanitize__", "__no_sanitize_address__", "__no_address_safety_analysis__", "__no_sanitize_thread__", "__leaf__", "__no_sanitize_undefined__", "__no_split_stack__", "__no_stack_limit__", "__noclone__", "__noipa__", "__nonnull__", "__noplt__", "__nothrow__", "__optimize__", "__pure__", "__patchable_function_entry__", "__returns_nonnull__", "__returns_twice__", "__section__", "__sentinel__", "__simd__", "__target_clones__", "__unused__", "__used__", "__visibility__", "__warn_unused_result__", "__params_nonnull__", "__weak__", "__vector_size__", "__ms_abi__", "__mode__", "__optnone__", "__nodebug__", -- "goto", "break", "return", "continue", "asm", "case", "default", "if", "else", "switch", "while", "for", "do", "sizeof", -- "typeof", "stdcall", "const_cast", "delete", "dynamic_cast", "goto", "namespace", "new", "true", "false", -- "reinterpret_cast", "static_cast", "this", "throw", "try", "catch", "using", "assert", "static_assert", "static", -- "alignas","alignof","concept","consteval","constexpr","constinit","co_await","co_return","co_yield","decltype", -- "noexcept","requires","thread_local", -- "compl", "and_eq", "or_eq", "xor_eq", "not", "not_eq", "bitand", "and", "bitor", "or", "xor", "pascal", "cdecl", } }, { Id=2, List= { "void", "int", "long", "short", "char", "signed", "unsigned", "float", "double", "size_t", "wint_t", "wchar_t", "bool", "_Bool", "int32_t", "uint_least64_t", "intptr_t", "uintmax_t", "int_fast32_t", "int16_t", "int64_t", "int_fast16_t", "int_fast64_t", "errno_t", "uint_fast32_t", "int_least8_t", "uint_least16_t", "char16_t", "uint_least32_t", "int_least64_t", "int_least16_t", "int_fast8_t", "uint_least8_t", "uintptr_t", "ssize_t", "int8_t", "int_least32_t", "uint8_t", "uint_fast64_t", "intmax_t", "uint_fast16_t", "uint32_t", "ptrdiff_t", "char32_t", "uint64_t", "uint16_t", "uint_fast8_t", "complex", "atomic_uintptr_t", "atomic_uchar", "atomic_int_least32_t", "atomic_uint_least64_t", "atomic_int_fast32_t", "atomic_uint_least16_t", "atomic_short", "atomic_size_t", "atomic_uint", "atomic_char16_t", "atomic_ullong", "atomic_uint_fast16_t", "atomic_int_fast8_t", "atomic_uint_least32_t", "atomic_ptrdiff_t", "atomic_uintmax_t", "atomic_int_least16_t", "atomic_long", "atomic_int", "atomic_int_fast16_t", "atomic_uint_least8_t", "atomic_ushort", "atomic_int_least8_t", "atomic_ulong", "atomic_char32_t", "atomic_schar", "atomic_intmax_t", "atomic_int_least64_t", "atomic_uint_fast64_t", "atomic_wchar_t", "atomic_uint_fast8_t", "atomic_int_fast64_t", "atomic_llong", "atomic_bool", "atomic_intptr_t", "atomic_uint_fast32_t", "atomic_char", "__int128", "_Float16", "_Complex", "_Float16x", "_Float32", "_Float32x", "_Float64", "_Float64x", "_Float128", "_Float128x", "int_least128_t", "int_fast128_t", "bool32", "int128_t", "uint128_t", "axdx_t", "__v8hu", "__v16qi", "__v4su", "__v8su", "__v16qu", "__v16qs", "__v8hi", "__v4hi", "__v2df", "__v2di", "__v4si", "__v8si", "__m1", "__v2du", "__m2", "__v1di", "__v4sf", "__v8sf", "__v2si", "__m64", "__v2sf", "__v8qi", "__v32qi", "__m128", "__m128d", "__m128i", "__m128_u", "__m128d_u", "__m128i_u", "__m256", "__m256d", "__m256i", "__m256_u", "__m256d_u", "__m256i_u", -- "int", "long", "short", "char", "void", "signed", "unsigned", "float", "double", "size_t", "wchar_t", -- "ptrdiff_t", "sig_atomic_t", "fpos_t", "clock_t", "time_t", "va_list", "jmp_buf", "FILE", "DIR", "div_t", "ldiv_t", -- "mbstate_t", "wctrans_t", "wint_t", "wctype_t", "const", "bool", "complex", "struct", "union", "enum", -- "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t", "int_least8_t", "int_least16_t", -- "int_least32_t", "int_least64_t", "uint_least8_t", "uint_least16_t", "uint_least32_t", "uint_least64_t", -- "int_fast8_t", "int_fast16_t", "int_fast32_t", "int_fast64_t", "uint_fast8_t", "uint_fast16_t", "uint_fast32_t", -- "uint_fast64_t", "intptr_t", "uintptr_t", "intmax_t", "uintmax_t", "char8_t","char16_t","char32_t" } }, { Id=3, List= { "static_assert", "__VA_OPT__", "__COUNTER__", "__SIG_ATOMIC_TYPE__", "__INT8_TYPE__", "__INT16_TYPE__", "__INT32_TYPE__", "__INT64_TYPE__", "__UINT8_TYPE__", "__UINT16_TYPE__", "__UINT32_TYPE__", "__UINT64_TYPE__", "__INT_LEAST8_TYPE__", "__INT_LEAST16_TYPE__", "__INT_LEAST32_TYPE__", "__INT_LEAST64_TYPE__", "__UINT_LEAST8_TYPE__", "__UINT_LEAST16_TYPE__", "__UINT_LEAST32_TYPE__", "__UINT_LEAST64_TYPE__", "__INT_FAST8_TYPE__", "__INT_FAST16_TYPE__", "__INT_FAST32_TYPE__", "__INT_FAST64_TYPE__", "__UINT_FAST8_TYPE__", "__UINT_FAST16_TYPE__", "__UINT_FAST32_TYPE__", "__UINT_FAST64_TYPE__", "__INTPTR_TYPE__", "__UINTPTR_TYPE__", "__INT8_C", "__INT16_C", "__INT32_C", "__INT64_C", "__UINT8_C", "__UINT16_C", "__UINT32_C", "__UINT64_C", "__INTMAX_C", "__UINTMAX_C", "__TIMESTAMP__", "__FP_FAST_FMA", "__FP_FAST_FMAF", "__FP_FAST_FMAL", "__FP_FAST_FMAF16", "__FP_FAST_FMAF32", "__FP_FAST_FMAF64", "__FP_FAST_FMAF128", "__FP_FAST_FMAF32X", "__FP_FAST_FMAF64X", "__FP_FAST_FMAF128X", "__builtin_va_list", "__has_attribute", "__has_builtin", "__has_cpp_attribute", "__builtin_va_arg", "__builtin_va_copy", "__builtin_va_start", "__builtin_va_end", "__builtin_abs", "__builtin_strcpy", "__builtin_stpcpy", "__builtin_setjmp", "__builtin_longjmp", "__builtin_apply_args", "__builtin_apply", "__builtin_return", "__builtin_va_arg_pack", "__builtin_va_arg_pack_len", "__builtin_constant_p", "__builtin_return_address", "__builtin_extract_return_addr", "__builtin_frob_return_address", "__builtin_frame_address", "__builtin_shuffle", "__builtin_convertvector", "__builtin_offsetof", "__builtin_add_overflow", "__builtin_sadd_overflow", "__builtin_saddl_overflow", "__builtin_saddll_overflow", "__builtin_uadd_overflow", "__builtin_uaddl_overflow", "__builtin_uaddll_overflow", "__builtin_sub_overflow", "__builtin_ssub_overflow", "__builtin_ssubl_overflow", "__builtin_ssubll_overflow", "__builtin_usub_overflow", "__builtin_usubl_overflow", "__builtin_usubll_overflow", "__builtin_mul_overflow", "__builtin_smul_overflow", "__builtin_smull_overflow", "__builtin_smulll_overflow", "__builtin_umul_overflow", "__builtin_umull_overflow", "__builtin_umulll_overflow", "__builtin_add_overflow_p", "__builtin_sub_overflow_p", "__builtin_mul_overflow_p", "__builtin_object_size", "__builtin___memcpy_chk", "__builtin___sprintf_chk", "__builtin___snprintf_chk", "__builtin___vsprintf_chk", "__builtin___vsnprintf_chk", "__builtin_alloca", "__builtin_alloca_with_align", "__builtin_alloc", "__builtin_alloca_with_align_and_max", "__builtin_has_attribute", "__builtin_speculation_safe_value", "__builtin_types_compatible_p", "__builtin_call_with_static_chain", "__builtin_choose_expr", "__builtin_tgmath", "__builtin_complex", "__builtin_is_constant_evaluated", "__builtin_expect", "__builtin_trap", "__builtin_unreachable", "__builtin_assume_aligned", "__builtin_LINE", "__builtin_FUNCTION", "__builtin_FILE", "__builtin___clear_cache", "__builtin_prefetch", "__builtin_huge_val", "__builtin_huge_valf", "__builtin_huge_vall", "__builtin_huge_valfn", "__builtin_huge_valfnx", "__builtin_fpclassify", "__builtin_inf", "__builtin_infd32", "__builtin_infd64", "__builtin_infd128", "__builtin_inff", "__builtin_infl", "__builtin_inffn", "__builtin_inffnx", "__builtin_isnan", "__builtin_signbit", "__builtin_signbitf", "__builtin_signbitl", "__builtin_isfinite", "__builtin_isinf", "__builtin_isinfinite", "__builtin_isnormal", "__builtin_isinf_sign", "__builtin_isgreater", "__builtin_isgreaterequal", "__builtin_isgreater", "__builtin_isgreaterequal", "__builtin_isless", "__builtin_islessequal", "__builtin_islessgreater", "__builtin_isunordered", "__builtin_nan", "__builtin_nand32", "__builtin_nand64", "__builtin_nand128", "__builtin_nanf", "__builtin_nanl", "__builtin_nanfn", "__builtin_nanfnx", "__builtin_nans", "__builtin_nansf", "__builtin_nansl", "__builtin_nansfn", "__builtin_nansfnx", "__builtin_ffs", "__builtin_clz", "__builtin_ctz", "__builtin_clrsb", "__builtin_popcount", "__builtin_parity", "__builtin_ffsl", "__builtin_clzl", "__builtin_ctzl", "__builtin_clrsbl", "__builtin_popcountl", "__builtin_parityl", "__builtin_ffsll", "__builtin_clzll", "__builtin_ctzll", "__builtin_clrsbll", "__builtin_popcountll", "__builtin_parityll", "__builtin_powi", "__builtin_powif", "__builtin_powil", "__builtin_bswap16", "__builtin_bswap32", "__builtin_bswap64", "__builtin_extend_pointer", "__builtin_goacc_parlevel_id", "__builtin_goacc_parlevel_size", "__builtin_fabsq", "__builtin_copysignq", "__builtin_infq", "__builtin_huge_valq", "__builtin_nanq", "__builtin_nansq", "__builtin_copysign", "__builtin_copysignf", "__builtin_copysignl", "__builtin_fabs", "__builtin_fabsf", "__builtin_fabsl", "__builtin_ceil", "__builtin_ceilf", "__builtin_ceill", "__builtin_floor", "__builtin_floorf", "__builtin_floorl", "__builtin_trunc", "__builtin_truncf", "__builtin_truncl", "__builtin_round", "__builtin_roundf", "__builtin_roundl", "__builtin_lround", "__builtin_lroundf", "__builtin_lroundl", "__builtin_nearbyint", "__builtin_nearbyintf", "__builtin_nearbyintl", "__builtin_scalbn", "__builtin_scalbnf", "__builtin_scalbnl", "__builtin_logb", "__builtin_logbf", "__builtin_logbl", "__builtin_fmax", "__builtin_fmaxf", "__builtin_fmaxl", "__builtin_fmin", "__builtin_fminf", "__builtin_fminl", "__builtin_rint", "__builtin_rintf", "__builtin_rintl", "__builtin_lrint", "__builtin_lrintf", "__builtin_lrintl", "__builtin_memcpy", "__builtin_memcmp", "__builtin_memset", "__builtin_strlen", "__atomic_load_n", "__atomic_load", "__atomic_store", "__atomic_store_n", "__atomic_exchange_n", "__atomic_exchange", "__atomic_compare_exchange_n", "__atomic_compare_exchange", "__atomic_add_fetch", "__atomic_sub_fetch", "__atomic_and_fetch", "__atomic_xor_fetch", "__atomic_or_fetch", "__atomic_nand_fetch", "__atomic_fetch_add", "__atomic_fetch_sub", "__atomic_fetch_and", "__atomic_fetch_xor", "__atomic_fetch_or", "__atomic_fetch_nand", "__atomic_test_and_set", "__atomic_clear", "__atomic_thread_fence", "__atomic_signal_fence", "__atomic_always_lock_free", "__atomic_is_lock_free", "__sync_fetch_and_add", "__sync_fetch_and_sub", "__sync_fetch_and_or", "__sync_fetch_and_and", "__sync_fetch_and_xor", "__sync_fetch_and_nand", "__sync_add_and_fetch", "__sync_sub_and_fetch", "__sync_or_and_fetch", "__sync_and_and_fetch", "__sync_xor_and_fetch", "__sync_nand_and_fetch", "__sync_bool_compare_and_swap", "__sync_val_compare_and_swap", "__sync_synchronize", "__sync_lock_test_and_set", "__sync_lock_release", "__builtin_ia32_pause", "__builtin_ia32_paddb", "__builtin_ia32_paddw", "__builtin_ia32_paddd", "__builtin_ia32_psubb", "__builtin_ia32_psubw", "__builtin_ia32_psubd", "__builtin_ia32_paddsb", "__builtin_ia32_paddsw", "__builtin_ia32_psubsb", "__builtin_ia32_psubsw", "__builtin_ia32_paddusb", "__builtin_ia32_paddusw", "__builtin_ia32_psubusb", "__builtin_ia32_psubusw", "__builtin_ia32_pmullw", "__builtin_ia32_pmulhw", "__builtin_ia32_pand", "__builtin_ia32_pandn", "__builtin_ia32_por", "__builtin_ia32_pxor", "__builtin_ia32_pcmpeqb", "__builtin_ia32_pcmpeqw", "__builtin_ia32_pcmpeqd", "__builtin_ia32_pcmpgtb", "__builtin_ia32_pcmpgtw", "__builtin_ia32_pcmpgtd", "__builtin_ia32_punpckhbw", "__builtin_ia32_punpckhwd", "__builtin_ia32_punpckhdq", "__builtin_ia32_punpcklbw", "__builtin_ia32_punpcklwd", "__builtin_ia32_punpckldq", "__builtin_ia32_packsswb", "__builtin_ia32_packssdw", "__builtin_ia32_packuswb", "__builtin_ia32_psllw", "__builtin_ia32_pslld", "__builtin_ia32_psllq", "__builtin_ia32_psrlw", "__builtin_ia32_psrld", "__builtin_ia32_psrlq", "__builtin_ia32_psraw", "__builtin_ia32_psrad", "__builtin_ia32_psllwi", "__builtin_ia32_pslldi", "__builtin_ia32_psllqi", "__builtin_ia32_psrlwi", "__builtin_ia32_psrldi", "__builtin_ia32_psrlqi", "__builtin_ia32_psrawi", "__builtin_ia32_psradi", "__builtin_ia32_pmulhuw", "__builtin_ia32_pavgb", "__builtin_ia32_pavgw", "__builtin_ia32_psadbw", "__builtin_ia32_pmaxub", "__builtin_ia32_pmaxsw", "__builtin_ia32_pminub", "__builtin_ia32_pminsw", "__builtin_ia32_pmovmskb", "__builtin_ia32_maskmovq", "__builtin_ia32_movntq", "__builtin_ia32_sfence", "__builtin_ia32_comieq", "__builtin_ia32_comineq", "__builtin_ia32_comilt", "__builtin_ia32_comile", "__builtin_ia32_comigt", "__builtin_ia32_comige", "__builtin_ia32_ucomieq", "__builtin_ia32_ucomineq", "__builtin_ia32_ucomilt", "__builtin_ia32_ucomile", "__builtin_ia32_ucomigt", "__builtin_ia32_ucomige", "__builtin_ia32_addps", "__builtin_ia32_subps", "__builtin_ia32_mulps", "__builtin_ia32_divps", "__builtin_ia32_addss", "__builtin_ia32_subss", "__builtin_ia32_mulss", "__builtin_ia32_divss", "__builtin_ia32_cmpeqps", "__builtin_ia32_cmpltps", "__builtin_ia32_cmpleps", "__builtin_ia32_cmpgtps", "__builtin_ia32_cmpgeps", "__builtin_ia32_cmpunordps", "__builtin_ia32_cmpneqps", "__builtin_ia32_cmpnltps", "__builtin_ia32_cmpnleps", "__builtin_ia32_cmpngtps", "__builtin_ia32_cmpngeps", "__builtin_ia32_cmpordps", "__builtin_ia32_cmpeqss", "__builtin_ia32_cmpltss", "__builtin_ia32_cmpless", "__builtin_ia32_cmpunordss", "__builtin_ia32_cmpneqss", "__builtin_ia32_cmpnltss", "__builtin_ia32_cmpnless", "__builtin_ia32_cmpordss", "__builtin_ia32_maxps", "__builtin_ia32_maxss", "__builtin_ia32_minps", "__builtin_ia32_minss", "__builtin_ia32_andps", "__builtin_ia32_andnps", "__builtin_ia32_orps", "__builtin_ia32_xorps", "__builtin_ia32_movss", "__builtin_ia32_movhlps", "__builtin_ia32_movlhps", "__builtin_ia32_unpckhps", "__builtin_ia32_unpcklps", "__builtin_ia32_cvtpi2ps", "__builtin_ia32_cvtsi2ss", "__builtin_ia32_cvtps2pi", "__builtin_ia32_cvtss2si", "__builtin_ia32_cvttps2pi", "__builtin_ia32_cvttss2si", "__builtin_ia32_rcpps", "__builtin_ia32_rsqrtps", "__builtin_ia32_sqrtps", "__builtin_ia32_rcpss", "__builtin_ia32_rsqrtss", "__builtin_ia32_sqrtss", "__builtin_ia32_shufps", "__builtin_ia32_movntps", "__builtin_ia32_movmskps", "__builtin_ia32_loadups", "__builtin_ia32_storeups", "__builtin_ia32_loadss", "__builtin_ia32_loadhps", "__builtin_ia32_loadlps", "__builtin_ia32_storehps", "__builtin_ia32_storelps", "__builtin_ia32_comisdeq", "__builtin_ia32_comisdlt", "__builtin_ia32_comisdle", "__builtin_ia32_comisdgt", "__builtin_ia32_comisdge", "__builtin_ia32_comisdneq", "__builtin_ia32_ucomisdeq", "__builtin_ia32_ucomisdlt", "__builtin_ia32_ucomisdle", "__builtin_ia32_ucomisdgt", "__builtin_ia32_ucomisdge", "__builtin_ia32_ucomisdneq", "__builtin_ia32_cmpeqpd", "__builtin_ia32_cmpltpd", "__builtin_ia32_cmplepd", "__builtin_ia32_cmpgtpd", "__builtin_ia32_cmpgepd", "__builtin_ia32_cmpunordpd", "__builtin_ia32_cmpneqpd", "__builtin_ia32_cmpnltpd", "__builtin_ia32_cmpnlepd", "__builtin_ia32_cmpngtpd", "__builtin_ia32_cmpngepd", "__builtin_ia32_cmpordpd", "__builtin_ia32_cmpeqsd", "__builtin_ia32_cmpltsd", "__builtin_ia32_cmplesd", "__builtin_ia32_cmpunordsd", "__builtin_ia32_cmpneqsd", "__builtin_ia32_cmpnltsd", "__builtin_ia32_cmpnlesd", "__builtin_ia32_cmpordsd", "__builtin_ia32_paddq", "__builtin_ia32_psubq", "__builtin_ia32_addpd", "__builtin_ia32_subpd", "__builtin_ia32_mulpd", "__builtin_ia32_divpd", "__builtin_ia32_addsd", "__builtin_ia32_subsd", "__builtin_ia32_mulsd", "__builtin_ia32_divsd", "__builtin_ia32_minpd", "__builtin_ia32_maxpd", "__builtin_ia32_minsd", "__builtin_ia32_maxsd", "__builtin_ia32_andpd", "__builtin_ia32_andnpd", "__builtin_ia32_orpd", "__builtin_ia32_xorpd", "__builtin_ia32_movsd", "__builtin_ia32_unpckhpd", "__builtin_ia32_unpcklpd", "__builtin_ia32_paddb128", "__builtin_ia32_paddw128", "__builtin_ia32_paddd128", "__builtin_ia32_paddq128", "__builtin_ia32_psubb128", "__builtin_ia32_psubw128", "__builtin_ia32_psubd128", "__builtin_ia32_psubq128", "__builtin_ia32_pmullw128", "__builtin_ia32_pmulhw128", "__builtin_ia32_pand128", "__builtin_ia32_pandn128", "__builtin_ia32_por128", "__builtin_ia32_pxor128", "__builtin_ia32_pavgb128", "__builtin_ia32_pavgw128", "__builtin_ia32_pcmpeqb128", "__builtin_ia32_pcmpeqw128", "__builtin_ia32_pcmpeqd128", "__builtin_ia32_pcmpgtb128", "__builtin_ia32_pcmpgtw128", "__builtin_ia32_pcmpgtd128", "__builtin_ia32_pmaxub128", "__builtin_ia32_pmaxsw128", "__builtin_ia32_pminub128", "__builtin_ia32_pminsw128", "__builtin_ia32_punpckhbw128", "__builtin_ia32_punpckhwd128", "__builtin_ia32_punpckhdq128", "__builtin_ia32_punpckhqdq128", "__builtin_ia32_punpcklbw128", "__builtin_ia32_punpcklwd128", "__builtin_ia32_punpckldq128", "__builtin_ia32_punpcklqdq128", "__builtin_ia32_packsswb128", "__builtin_ia32_packssdw128", "__builtin_ia32_packuswb128", "__builtin_ia32_pmulhuw128", "__builtin_ia32_maskmovdqu", "__builtin_ia32_loadupd", "__builtin_ia32_storeupd", "__builtin_ia32_loadhpd", "__builtin_ia32_loadlpd", "__builtin_ia32_movmskpd", "__builtin_ia32_pmovmskb128", "__builtin_ia32_movnti", "__builtin_ia32_movnti64", "__builtin_ia32_movntpd", "__builtin_ia32_movntdq", "__builtin_ia32_pshufd", "__builtin_ia32_pshuflw", "__builtin_ia32_pshufhw", "__builtin_ia32_psadbw128", "__builtin_ia32_sqrtpd", "__builtin_ia32_sqrtsd", "__builtin_ia32_shufpd", "__builtin_ia32_cvtdq2pd", "__builtin_ia32_cvtdq2ps", "__builtin_ia32_cvtpd2dq", "__builtin_ia32_cvtpd2pi", "__builtin_ia32_cvtpd2ps", "__builtin_ia32_cvttpd2dq", "__builtin_ia32_cvttpd2pi", "__builtin_ia32_cvtpi2pd", "__builtin_ia32_cvtsd2si", "__builtin_ia32_cvttsd2si", "__builtin_ia32_cvtsd2si64", "__builtin_ia32_cvttsd2si64", "__builtin_ia32_cvtps2dq", "__builtin_ia32_cvtps2pd", "__builtin_ia32_cvttps2dq", "__builtin_ia32_cvtsi2sd", "__builtin_ia32_cvtsi642sd", "__builtin_ia32_cvtsd2ss", "__builtin_ia32_cvtss2sd", "__builtin_ia32_clflush", "__builtin_ia32_lfence", "__builtin_ia32_mfence", "__builtin_ia32_loaddqu", "__builtin_ia32_storedqu", "__builtin_ia32_pmuludq", "__builtin_ia32_pmuludq128", "__builtin_ia32_psllw128", "__builtin_ia32_pslld128", "__builtin_ia32_psllq128", "__builtin_ia32_psrlw128", "__builtin_ia32_psrld128", "__builtin_ia32_psrlq128", "__builtin_ia32_psraw128", "__builtin_ia32_psrad128", "__builtin_ia32_pslldqi128", "__builtin_ia32_psllwi128", "__builtin_ia32_pslldi128", "__builtin_ia32_psllqi128", "__builtin_ia32_psrldqi128", "__builtin_ia32_psrlwi128", "__builtin_ia32_psrldi128", "__builtin_ia32_psrlqi128", "__builtin_ia32_psrawi128", "__builtin_ia32_psradi128", "__builtin_ia32_pmaddwd128", "__builtin_ia32_movq128", "__builtin_ia32_addsubpd", "__builtin_ia32_addsubps", "__builtin_ia32_haddpd", "__builtin_ia32_haddps", "__builtin_ia32_hsubpd", "__builtin_ia32_hsubps", "__builtin_ia32_lddqu", "__builtin_ia32_monitor", "__builtin_ia32_movshdup", "__builtin_ia32_movsldup", "__builtin_ia32_mwait", "__builtin_ia32_phaddd", "__builtin_ia32_phaddw", "__builtin_ia32_phaddsw", "__builtin_ia32_phsubd", "__builtin_ia32_phsubw", "__builtin_ia32_phsubsw", "__builtin_ia32_pmaddubsw", "__builtin_ia32_pmulhrsw", "__builtin_ia32_pshufb", "__builtin_ia32_psignb", "__builtin_ia32_psignd", "__builtin_ia32_psignw", "__builtin_ia32_palignr", "__builtin_ia32_pabsb", "__builtin_ia32_pabsd", "__builtin_ia32_pabsw", "__builtin_ia32_phaddd128", "__builtin_ia32_phaddw128", "__builtin_ia32_phaddsw128", "__builtin_ia32_phsubd128", "__builtin_ia32_phsubw128", "__builtin_ia32_phsubsw128", "__builtin_ia32_pmaddubsw128", "__builtin_ia32_pmulhrsw128", "__builtin_ia32_pshufb128", "__builtin_ia32_psignb128", "__builtin_ia32_psignd128", "__builtin_ia32_psignw128", "__builtin_ia32_palignr128", "__builtin_ia32_pabsb128", "__builtin_ia32_pabsd128", "__builtin_ia32_pabsw128", "__builtin_ia32_blendpd", "__builtin_ia32_blendps", "__builtin_ia32_blendvpd", "__builtin_ia32_blendvps", "__builtin_ia32_dppd", "__builtin_ia32_dpps", "__builtin_ia32_insertps128", "__builtin_ia32_movntdqa", "__builtin_ia32_mpsadbw128", "__builtin_ia32_packusdw128", "__builtin_ia32_pblendvb128", "__builtin_ia32_pblendw128", "__builtin_ia32_pcmpeqq", "__builtin_ia32_phminposuw128", "__builtin_ia32_pmaxsb128", "__builtin_ia32_pmaxsd128", "__builtin_ia32_pmaxud128", "__builtin_ia32_pmaxuw128", "__builtin_ia32_pminsb128", "__builtin_ia32_pminsd128", "__builtin_ia32_pminud128", "__builtin_ia32_pminuw128", "__builtin_ia32_pmovsxbd128", "__builtin_ia32_pmovsxbq128", "__builtin_ia32_pmovsxbw128", "__builtin_ia32_pmovsxdq128", "__builtin_ia32_pmovsxwd128", "__builtin_ia32_pmovsxwq128", "__builtin_ia32_pmovzxbd128", "__builtin_ia32_pmovzxbq128", "__builtin_ia32_pmovzxbw128", "__builtin_ia32_pmovzxdq128", "__builtin_ia32_pmovzxwd128", "__builtin_ia32_pmovzxwq128", "__builtin_ia32_pmuldq128", "__builtin_ia32_pmulld128", "__builtin_ia32_ptestc128", "__builtin_ia32_ptestnzc128", "__builtin_ia32_ptestz128", "__builtin_ia32_roundpd", "__builtin_ia32_roundps", "__builtin_ia32_roundsd", "__builtin_ia32_roundss", "__builtin_ia32_vec_set_v4sf", "__builtin_ia32_vec_ext_v16qi", "__builtin_ia32_vec_set_v16qi", "__builtin_ia32_vec_set_v4si", "__builtin_ia32_vec_set_v2di", "__builtin_ia32_vec_ext_v4sf", "__builtin_ia32_vec_ext_v4si", "__builtin_ia32_vec_ext_v2di", "__builtin_ia32_pcmpestrm128", "__builtin_ia32_pcmpestri128", "__builtin_ia32_pcmpestria128", "__builtin_ia32_pcmpestric128", "__builtin_ia32_pcmpestrio128", "__builtin_ia32_pcmpestris128", "__builtin_ia32_pcmpestriz128", "__builtin_ia32_pcmpistrm128", "__builtin_ia32_pcmpistri128", "__builtin_ia32_pcmpistria128", "__builtin_ia32_pcmpistric128", "__builtin_ia32_pcmpistrio128", "__builtin_ia32_pcmpistris128", "__builtin_ia32_pcmpistriz128", "__builtin_ia32_pcmpgtq", "__builtin_ia32_crc32qi", "__builtin_ia32_crc32hi", "__builtin_ia32_crc32si", "__builtin_ia32_crc32di", "__builtin_ia32_addpd256", "__builtin_ia32_addps256", "__builtin_ia32_addsubpd256", "__builtin_ia32_addsubps256", "__builtin_ia32_andnpd256", "__builtin_ia32_andnps256", "__builtin_ia32_andpd256", "__builtin_ia32_andps256", "__builtin_ia32_blendpd256", "__builtin_ia32_blendps256", "__builtin_ia32_blendvpd256", "__builtin_ia32_blendvps256", "__builtin_ia32_cmppd", "__builtin_ia32_cmppd256", "__builtin_ia32_cmpps", "__builtin_ia32_cmpps256", "__builtin_ia32_cmpsd", "__builtin_ia32_cmpss", "__builtin_ia32_cvtdq2pd256", "__builtin_ia32_cvtdq2ps256", "__builtin_ia32_cvtpd2dq256", "__builtin_ia32_cvtpd2ps256", "__builtin_ia32_cvtps2dq256", "__builtin_ia32_cvtps2pd256", "__builtin_ia32_cvttpd2dq256", "__builtin_ia32_cvttps2dq256", "__builtin_ia32_divpd256", "__builtin_ia32_divps256", "__builtin_ia32_dpps256", "__builtin_ia32_haddpd256", "__builtin_ia32_haddps256", "__builtin_ia32_hsubpd256", "__builtin_ia32_hsubps256", "__builtin_ia32_lddqu256", "__builtin_ia32_loaddqu256", "__builtin_ia32_loadupd256", "__builtin_ia32_loadups256", "__builtin_ia32_maskloadpd", "__builtin_ia32_maskloadpd256", "__builtin_ia32_maskloadps", "__builtin_ia32_maskloadps256", "__builtin_ia32_maskstorepd", "__builtin_ia32_maskstorepd256", "__builtin_ia32_maskstoreps", "__builtin_ia32_maskstoreps256", "__builtin_ia32_maxpd256", "__builtin_ia32_maxps256", "__builtin_ia32_minpd256", "__builtin_ia32_minps256", "__builtin_ia32_movddup256", "__builtin_ia32_movmskpd256", "__builtin_ia32_movmskps256", "__builtin_ia32_movshdup256", "__builtin_ia32_movsldup256", "__builtin_ia32_mulpd256", "__builtin_ia32_mulps256", "__builtin_ia32_orpd256", "__builtin_ia32_orps256", "__builtin_ia32_pd_pd256", "__builtin_ia32_pd256_pd", "__builtin_ia32_ps_ps256", "__builtin_ia32_ps256_ps", "__builtin_ia32_ptestc256", "__builtin_ia32_ptestnzc256", "__builtin_ia32_ptestz256", "__builtin_ia32_rcpps256", "__builtin_ia32_roundpd256", "__builtin_ia32_roundps256", "__builtin_ia32_rsqrtps_nr256", "__builtin_ia32_rsqrtps256", "__builtin_ia32_shufpd256", "__builtin_ia32_shufps256", "__builtin_ia32_si_si256", "__builtin_ia32_si256_si", "__builtin_ia32_sqrtpd256", "__builtin_ia32_sqrtps_nr256", "__builtin_ia32_sqrtps256", "__builtin_ia32_storedqu256", "__builtin_ia32_storeupd256", "__builtin_ia32_storeups256", "__builtin_ia32_subpd256", "__builtin_ia32_subps256", "__builtin_ia32_unpckhpd256", "__builtin_ia32_unpckhps256", "__builtin_ia32_unpcklpd256", "__builtin_ia32_unpcklps256", "__builtin_ia32_vbroadcastf128_pd256", "__builtin_ia32_vbroadcastf128_ps256", "__builtin_ia32_vbroadcastsd256", "__builtin_ia32_vbroadcastss", "__builtin_ia32_vbroadcastss256", "__builtin_ia32_vextractf128_pd256", "__builtin_ia32_vextractf128_ps256", "__builtin_ia32_vextractf128_si256", "__builtin_ia32_vinsertf128_pd256", "__builtin_ia32_vinsertf128_ps256", "__builtin_ia32_vinsertf128_si256", "__builtin_ia32_vperm2f128_pd256", "__builtin_ia32_vperm2f128_ps256", "__builtin_ia32_vperm2f128_si256", "__builtin_ia32_vpermil2pd", "__builtin_ia32_vpermil2pd256", "__builtin_ia32_vpermil2ps", "__builtin_ia32_vpermil2ps256", "__builtin_ia32_vpermilpd", "__builtin_ia32_vpermilpd256", "__builtin_ia32_vpermilps", "__builtin_ia32_vpermilps256", "__builtin_ia32_vpermilvarpd", "__builtin_ia32_vpermilvarpd256", "__builtin_ia32_vpermilvarps", "__builtin_ia32_vpermilvarps256", "__builtin_ia32_vtestcpd", "__builtin_ia32_vtestcpd256", "__builtin_ia32_vtestcps", "__builtin_ia32_vtestcps256", "__builtin_ia32_vtestnzcpd", "__builtin_ia32_vtestnzcpd256", "__builtin_ia32_vtestnzcps", "__builtin_ia32_vtestnzcps256", "__builtin_ia32_vtestzpd", "__builtin_ia32_vtestzpd256", "__builtin_ia32_vtestzps", "__builtin_ia32_vtestzps256", "__builtin_ia32_vzeroall", "__builtin_ia32_vzeroupper", "__builtin_ia32_xorpd256", "__builtin_ia32_xorps256", "__builtin_ia32_mpsadbw256", "__builtin_ia32_pabsb256", "__builtin_ia32_pabsw256", "__builtin_ia32_pabsd256", "__builtin_ia32_packssdw256", "__builtin_ia32_packsswb256", "__builtin_ia32_packusdw256", "__builtin_ia32_packuswb256", "__builtin_ia32_paddb256", "__builtin_ia32_paddw256", "__builtin_ia32_paddd256", "__builtin_ia32_paddq256", "__builtin_ia32_paddsb256", "__builtin_ia32_paddsw256", "__builtin_ia32_paddusb256", "__builtin_ia32_paddusw256", "__builtin_ia32_palignr256", "__builtin_ia32_andsi256", "__builtin_ia32_andnotsi256", "__builtin_ia32_pavgb256", "__builtin_ia32_pavgw256", "__builtin_ia32_pblendvb256", "__builtin_ia32_pblendw256", "__builtin_ia32_pcmpeqb256", "__builtin_ia32_pcmpeqw256", "__builtin_ia32_pcmpeqd256", "__builtin_ia32_pcmpeqq256", "__builtin_ia32_pcmpgtb256", "__builtin_ia32_pcmpgtw256", "__builtin_ia32_pcmpgtd256", "__builtin_ia32_pcmpgtq256", "__builtin_ia32_phaddw256", "__builtin_ia32_phaddd256", "__builtin_ia32_phaddsw256", "__builtin_ia32_phsubw256", "__builtin_ia32_phsubd256", "__builtin_ia32_phsubsw256", "__builtin_ia32_pmaddubsw256", "__builtin_ia32_pmaddwd256", "__builtin_ia32_pmaxsb256", "__builtin_ia32_pmaxsw256", "__builtin_ia32_pmaxsd256", "__builtin_ia32_pmaxub256", "__builtin_ia32_pmaxuw256", "__builtin_ia32_pmaxud256", "__builtin_ia32_pminsb256", "__builtin_ia32_pminsw256", "__builtin_ia32_pminsd256", "__builtin_ia32_pminub256", "__builtin_ia32_pminuw256", "__builtin_ia32_pminud256", "__builtin_ia32_pmovmskb256", "__builtin_ia32_pmovsxbw256", "__builtin_ia32_pmovsxbd256", "__builtin_ia32_pmovsxbq256", "__builtin_ia32_pmovsxwd256", "__builtin_ia32_pmovsxwq256", "__builtin_ia32_pmovsxdq256", "__builtin_ia32_pmovzxbw256", "__builtin_ia32_pmovzxbd256", "__builtin_ia32_pmovzxbq256", "__builtin_ia32_pmovzxwd256", "__builtin_ia32_pmovzxwq256", "__builtin_ia32_pmovzxdq256", "__builtin_ia32_pmuldq256", "__builtin_ia32_pmulhrsw256", "__builtin_ia32_pmulhuw256", "__builtin_ia32_pmulhw256", "__builtin_ia32_pmullw256", "__builtin_ia32_pmulld256", "__builtin_ia32_pmuludq256", "__builtin_ia32_por256", "__builtin_ia32_psadbw256", "__builtin_ia32_pshufb256", "__builtin_ia32_pshufd256", "__builtin_ia32_pshufhw256", "__builtin_ia32_pshuflw256", "__builtin_ia32_psignb256", "__builtin_ia32_psignw256", "__builtin_ia32_psignd256", "__builtin_ia32_pslldqi256", "__builtin_ia32_psllwi256", "__builtin_ia32_pslldi256", "__builtin_ia32_psllqi256", "__builtin_ia32_psrawi256", "__builtin_ia32_psraw256", "__builtin_ia32_psradi256", "__builtin_ia32_psrad256", "__builtin_ia32_psrldqi256", "__builtin_ia32_psrlwi256", "__builtin_ia32_psrlw256", "__builtin_ia32_psrldi256", "__builtin_ia32_psrld256", "__builtin_ia32_psrlqi256", "__builtin_ia32_psubb256", "__builtin_ia32_psubw256", "__builtin_ia32_psubd256", "__builtin_ia32_psubq256", "__builtin_ia32_psubsb256", "__builtin_ia32_psubsw256", "__builtin_ia32_psubusb256", "__builtin_ia32_psubusw256", "__builtin_ia32_punpckhbw256", "__builtin_ia32_punpckhwd256", "__builtin_ia32_punpckhdq256", "__builtin_ia32_punpckhqdq256", "__builtin_ia32_punpcklbw256", "__builtin_ia32_punpcklwd256", "__builtin_ia32_punpckldq256", "__builtin_ia32_punpcklqdq256", "__builtin_ia32_pxor256", "__builtin_ia32_movntdqa256", "__builtin_ia32_vbroadcastss_ps", "__builtin_ia32_vbroadcastss_ps256", "__builtin_ia32_vbroadcastsd_pd256", "__builtin_ia32_vbroadcastsi256", "__builtin_ia32_pblendd128", "__builtin_ia32_pblendd256", "__builtin_ia32_pbroadcastb256", "__builtin_ia32_pbroadcastw256", "__builtin_ia32_pbroadcastd256", "__builtin_ia32_pbroadcastq256", "__builtin_ia32_pbroadcastb128", "__builtin_ia32_pbroadcastw128", "__builtin_ia32_pbroadcastd128", "__builtin_ia32_pbroadcastq128", "__builtin_ia32_permvarsi256", "__builtin_ia32_permdf256", "__builtin_ia32_permvarsf256", "__builtin_ia32_permdi256", "__builtin_ia32_permti256", "__builtin_ia32_extract128i256", "__builtin_ia32_insert128i256", "__builtin_ia32_maskloadd256", "__builtin_ia32_maskloadq256", "__builtin_ia32_maskloadd", "__builtin_ia32_maskloadq", "__builtin_ia32_maskstored256", "__builtin_ia32_maskstoreq256", "__builtin_ia32_maskstored", "__builtin_ia32_maskstoreq", "__builtin_ia32_psllv8si", "__builtin_ia32_psllv4si", "__builtin_ia32_psllv4di", "__builtin_ia32_psllv2di", "__builtin_ia32_psrav8si", "__builtin_ia32_psrav4si", "__builtin_ia32_psrlv8si", "__builtin_ia32_psrlv4si", "__builtin_ia32_psrlv4di", "__builtin_ia32_psrlv2di", "__builtin_ia32_gathersiv2df", "__builtin_ia32_gathersiv4df", "__builtin_ia32_gatherdiv2df", "__builtin_ia32_gatherdiv4df", "__builtin_ia32_gathersiv4sf", "__builtin_ia32_gathersiv8sf", "__builtin_ia32_gatherdiv4sf", "__builtin_ia32_gatherdiv4sf256", "__builtin_ia32_gathersiv2di", "__builtin_ia32_gathersiv4di", "__builtin_ia32_gatherdiv2di", "__builtin_ia32_gatherdiv4di", "__builtin_ia32_gathersiv4si", "__builtin_ia32_gathersiv8si", "__builtin_ia32_gatherdiv4si", "__builtin_ia32_gatherdiv4si256", "__builtin_ia32_aesenc128", "__builtin_ia32_aesenclast128", "__builtin_ia32_aesdec128", "__builtin_ia32_aesdeclast128", "__builtin_ia32_aeskeygenassist128", "__builtin_ia32_aesimc128", "__builtin_ia32_pclmulqdq128", "__builtin_ia32_rdfsbase32", "__builtin_ia32_rdfsbase64", "__builtin_ia32_rdgsbase32", "__builtin_ia32_rdgsbase64", "__builtin_ia32_rdrand16_step", "__builtin_ia32_rdrand32_step", "__builtin_ia32_rdrand64_step", "__builtin_ia32_ptwrite32", "__builtin_ia32_ptwrite64", "__builtin_ia32_movntsd", "__builtin_ia32_movntss", "__builtin_ia32_extrqi", "__builtin_ia32_insertq", "__builtin_ia32_insertqi", "__builtin_ia32_vfrczpd", "__builtin_ia32_vfrczps", "__builtin_ia32_vfrczsd", "__builtin_ia32_vfrczss", "__builtin_ia32_vfrczpd256", "__builtin_ia32_vfrczps256", "__builtin_ia32_vpcmov", "__builtin_ia32_vpcmov_v2di", "__builtin_ia32_vpcmov_v4si", "__builtin_ia32_vpcmov_v8hi", "__builtin_ia32_vpcmov_v16qi", "__builtin_ia32_vpcmov_v2df", "__builtin_ia32_vpcmov_v4sf", "__builtin_ia32_vpcmov_v4di256", "__builtin_ia32_vpcmov_v8si256", "__builtin_ia32_vpcmov_v16hi256", "__builtin_ia32_vpcmov_v32qi256", "__builtin_ia32_vpcmov_v4df256", "__builtin_ia32_vpcmov_v8sf256", "__builtin_ia32_vpcomeqb", "__builtin_ia32_vpcomeqw", "__builtin_ia32_vpcomeqd", "__builtin_ia32_vpcomeqq", "__builtin_ia32_vpcomequb", "__builtin_ia32_vpcomequd", "__builtin_ia32_vpcomequq", "__builtin_ia32_vpcomequw", "__builtin_ia32_vpcomfalseb", "__builtin_ia32_vpcomfalsed", "__builtin_ia32_vpcomfalseq", "__builtin_ia32_vpcomfalseub", "__builtin_ia32_vpcomfalseud", "__builtin_ia32_vpcomfalseuq", "__builtin_ia32_vpcomfalseuw", "__builtin_ia32_vpcomfalsew", "__builtin_ia32_vpcomgeb", "__builtin_ia32_vpcomged", "__builtin_ia32_vpcomgeq", "__builtin_ia32_vpcomgeub", "__builtin_ia32_vpcomgeud", "__builtin_ia32_vpcomgeuq", "__builtin_ia32_vpcomgeuw", "__builtin_ia32_vpcomgew", "__builtin_ia32_vpcomgtb", "__builtin_ia32_vpcomgtd", "__builtin_ia32_vpcomgtq", "__builtin_ia32_vpcomgtub", "__builtin_ia32_vpcomgtud", "__builtin_ia32_vpcomgtuq", "__builtin_ia32_vpcomgtuw", "__builtin_ia32_vpcomgtw", "__builtin_ia32_vpcomleb", "__builtin_ia32_vpcomled", "__builtin_ia32_vpcomleq", "__builtin_ia32_vpcomleub", "__builtin_ia32_vpcomleud", "__builtin_ia32_vpcomleuq", "__builtin_ia32_vpcomleuw", "__builtin_ia32_vpcomlew", "__builtin_ia32_vpcomltb", "__builtin_ia32_vpcomltd", "__builtin_ia32_vpcomltq", "__builtin_ia32_vpcomltub", "__builtin_ia32_vpcomltud", "__builtin_ia32_vpcomltuq", "__builtin_ia32_vpcomltuw", "__builtin_ia32_vpcomltw", "__builtin_ia32_vpcomneb", "__builtin_ia32_vpcomned", "__builtin_ia32_vpcomneq", "__builtin_ia32_vpcomneub", "__builtin_ia32_vpcomneud", "__builtin_ia32_vpcomneuq", "__builtin_ia32_vpcomneuw", "__builtin_ia32_vpcomnew", "__builtin_ia32_vpcomtrueb", "__builtin_ia32_vpcomtrued", "__builtin_ia32_vpcomtrueq", "__builtin_ia32_vpcomtrueub", "__builtin_ia32_vpcomtrueud", "__builtin_ia32_vpcomtrueuq", "__builtin_ia32_vpcomtrueuw", "__builtin_ia32_vpcomtruew", "__builtin_ia32_vphaddbd", "__builtin_ia32_vphaddbq", "__builtin_ia32_vphaddbw", "__builtin_ia32_vphadddq", "__builtin_ia32_vphaddubd", "__builtin_ia32_vphaddubq", "__builtin_ia32_vphaddubw", "__builtin_ia32_vphaddudq", "__builtin_ia32_vphadduwd", "__builtin_ia32_vphadduwq", "__builtin_ia32_vphaddwd", "__builtin_ia32_vphaddwq", "__builtin_ia32_vphsubbw", "__builtin_ia32_vphsubdq", "__builtin_ia32_vphsubwd", "__builtin_ia32_vpmacsdd", "__builtin_ia32_vpmacsdqh", "__builtin_ia32_vpmacsdql", "__builtin_ia32_vpmacssdd", "__builtin_ia32_vpmacssdqh", "__builtin_ia32_vpmacssdql", "__builtin_ia32_vpmacsswd", "__builtin_ia32_vpmacssww", "__builtin_ia32_vpmacswd", "__builtin_ia32_vpmacsww", "__builtin_ia32_vpmadcsswd", "__builtin_ia32_vpmadcswd", "__builtin_ia32_vpperm", "__builtin_ia32_vprotb", "__builtin_ia32_vprotd", "__builtin_ia32_vprotq", "__builtin_ia32_vprotw", "__builtin_ia32_vpshab", "__builtin_ia32_vpshad", "__builtin_ia32_vpshaq", "__builtin_ia32_vpshaw", "__builtin_ia32_vpshlb", "__builtin_ia32_vpshld", "__builtin_ia32_vpshlq", "__builtin_ia32_vpshlw", "__builtin_ia32_vfmaddpd", "__builtin_ia32_vfmaddps", "__builtin_ia32_vfmaddsd", "__builtin_ia32_vfmaddss", "__builtin_ia32_vfmsubpd", "__builtin_ia32_vfmsubps", "__builtin_ia32_vfmsubsd", "__builtin_ia32_vfmsubss", "__builtin_ia32_vfnmaddpd", "__builtin_ia32_vfnmaddps", "__builtin_ia32_vfnmaddsd", "__builtin_ia32_vfnmaddss", "__builtin_ia32_vfnmsubpd", "__builtin_ia32_vfnmsubps", "__builtin_ia32_vfnmsubsd", "__builtin_ia32_vfnmsubss", "__builtin_ia32_vfmaddpd256", "__builtin_ia32_vfmaddps256", "__builtin_ia32_vfmsubpd256", "__builtin_ia32_vfmsubps256", "__builtin_ia32_vfnmaddpd256", "__builtin_ia32_vfnmaddps256", "__builtin_ia32_vfnmsubpd256", "__builtin_ia32_vfnmsubps256", "__builtin_ia32_vfmaddsubpd256", "__builtin_ia32_vfmaddsubps256", "__builtin_ia32_vfmsubaddpd256", "__builtin_ia32_vfmsubaddps256", "__builtin_ia32_llwpcb16", "__builtin_ia32_llwpcb32", "__builtin_ia32_llwpcb64", "__builtin_ia32_lwpval16", "__builtin_ia32_lwpval32", "__builtin_ia32_lwpval64", "__builtin_ia32_lwpins16", "__builtin_ia32_lwpins32", "__builtin_ia32_lwpins64", "__builtin_ia32_bextr_u64", "__builtin_ia32_lzcnt_u64", "__builtin_ia32_fxsave", "__builtin_ia32_fxrstor", "__builtin_ia32_fxsave64", "__builtin_ia32_fxrstor64", "__builtin_ia32_xsave", "__builtin_ia32_xrstor", "__builtin_ia32_xsave64", "__builtin_ia32_xrstor64", "__builtin_ia32_xsaveopt", "__builtin_ia32_xsaveopt64", "__builtin_ia32_bextri_u32", "__builtin_ia32_bextri_u64", "__builtin_ia32_femms", "__builtin_ia32_pavgusb", "__builtin_ia32_pf2id", "__builtin_ia32_pfacc", "__builtin_ia32_pfadd", "__builtin_ia32_pfcmpeq", "__builtin_ia32_pfcmpge", "__builtin_ia32_pfcmpgt", "__builtin_ia32_pfmax", "__builtin_ia32_pfmin", "__builtin_ia32_pfmul", "__builtin_ia32_pfrcp", "__builtin_ia32_pfrcpit1", "__builtin_ia32_pfrcpit2", "__builtin_ia32_pfrsqrt", "__builtin_ia32_pfsub", "__builtin_ia32_pfsubr", "__builtin_ia32_pi2fd", "__builtin_ia32_pmulhrw", "__builtin_ia32_pf2iw", "__builtin_ia32_pfnacc", "__builtin_ia32_pfpnacc", "__builtin_ia32_pi2fw", "__builtin_ia32_pswapdsf", "__builtin_ia32_pswapdsi", "__builtin_ia32_xbegin", "__builtin_ia32_xend", "__builtin_ia32_xabort", "__builtin_ia32_xtest", "__builtin_ia32_monitorx", "__builtin_ia32_mwaitx", "__builtin_ia32_wrpkru", "__builtin_ia32_rdpkru", "__builtin_ia32_rdsspd", "__builtin_ia32_rdsspq", "__builtin_ia32_incsspd", "__builtin_ia32_incsspq", "__has_nothrow_assign", "__has_trivial_assign", "__has_nothrow_copy", "__has_trivial_copy", "__has_nothrow_constructor", "__has_trivial_constructor", "__is_pod", "__has_trivial_destructor", "__has_virtual_destructor", "__is_abstract", "__is_base_of", "__is_class", "__is_empty", "__is_enum", "__is_literal_type", "__is_polymorphic", "__is_standard_layout", "__is_trivial", "__is_union", "__underlying_type", "__integer_pack", "__is_same", "COSMOPOLITAN_CXX_START_", "COSMOPOLITAN_CXX_END_", "COSMOPOLITAN_CXX_USING_", "COSMOPOLITAN_C_START_", "COSMOPOLITAN_C_END_", "MACHINE_CODE_ANALYSIS_BEGIN_", "MACHINE_CODE_ANALYSIS_END_", "DebugBreak", "VEIL", "CONCEAL", "EXPROPRIATE", "YOINK", "STATIC_YOINK", "STATIC_YOINK_SOURCE", "STRINGIFY", "likely", "unlikely", "assume", } }, { Id=4, List= { "NULL", "true", "false", "__func__", "__VA_ARGS__", "__STDC__", "__STDC_HOSTED__", "__STDC_VERSION__", "__TIME__", "__STDC_ISO_10646__", "__STDC_MB_MIGHT_NEQ_WC__", "__STDC_UTF_16__", "__STDC_UTF_32__", "__STDC_ANALYZABLE__", "__STDC_IEC_559_COMPLEX__", "__STDC_LIB_EXT1__", "__STDC_NO_ATOMICS__", "__STDC_NO_COMPLEX__", "__STDC_NO_THREADS__", "__STDC_NO_VLA__", "__STDC_WANT_LIB_EXT1__", "IMAGE_BASE_VIRTUAL", "IMAGE_BASE_REAL", "IMAGE_BASE_PHYSICAL", "SCHAR_MAX", "SHRT_MAX", "INT_MAX", "LONG_MAX", "LLONG_MAX", "LONG_LONG_MAX", "SIZE_MAX", "SSIZE_MAX", "INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX", "INT128_MAX", "WINT_MAX", "WCHAR_MAX", "INTPTR_MAX", "PTRDIFF_MAX", "SCHAR_MIN", "SHRT_MIN", "UINT_MIN", "INT_MIN", "LONG_MIN", "LLONG_MIN", "LONG_LONG_MIN", "SIZE_MIN", "INT8_MIN", "INT16_MIN", "INT32_MIN", "INT64_MIN", "INT128_MIN", "INTMAX_MIN", "INTPTR_MIN", "WINT_MIN", "WCHAR_MIN", "PTRDIFF_MIN", "USHRT_MAX", "UINT_MAX", "ULONG_MAX", "ULLONG_MAX", "ULONG_LONG_MAX", "UINTPTR_MAX", "UINT8_MAX", "UINT16_MAX", "UINT32_MAX", "UINT64_MAX", "UINT128_MAX", "USHRT_MIN", "ULONG_MIN", "ULLONG_MIN", "ULONG_LONG_MIN", "UINT8_MIN", "UINT16_MIN", "UINT32_MIN", "UINT64_MIN", "UINT128_MIN", "UINTMAX_MIN", "UINTPTR_MIN", "MB_CUR_MAX", "MB_LEN_MAX", "INTMAX_MAX", "UINTMAX_MAX", "INTMAX_MAX", "UINTMAX_MAX", "DBL_MIN", "DBL_MAX", "FLT_MIN", "FLT_MAX", "__SAUCE__", "PAGESIZE", "FRAMESIZE", "BIGPAGESIZE", "STACKSIZE", "ARG_MAX", "PATH_MAX", "BUFSIZ", "CACHELINE", "CHAR_BIT", "NAME_MAX", "NSIG", "CHILD_MAX", "OPEN_MAX", "ATEXIT_MAX", "IM_FEELING_NAUGHTY", "__REAL_MODE__", "__x86__", "__i386__", "__W__", "__PG__", "__MFENTRY__", "__MNO_VZEROUPPER__", "__SANITIZE_ADDRESS__", "__SANITIZE_UNDEFINED__", "__MNOP_MCOUNT__", "__MRECORD_MCOUNT__", "__x86_64__", "__amd64__", "__WINT_MAX__", "__BIGGEST_ALIGNMENT__", "__SIZE_MAX__", "__PTRDIFF_MAX__", "__UINTMAX_MAX__", "__SIG_ATOMIC_MAX__", "__INT8_MAX__", "__INT16_MAX__", "__INT32_MAX__", "__INT64_MAX__", "__UINT8_MAX__", "__UINT16_MAX__", "__UINT32_MAX__", "__UINT64_MAX__", "__INT_LEAST8_MAX__", "__INT_LEAST16_MAX__", "__INT_LEAST32_MAX__", "__INT_LEAST64_MAX__", "__UINT_LEAST8_MAX__", "__UINT_LEAST16_MAX__", "__UINT_LEAST32_MAX__", "__UINT_LEAST64_MAX__", "__INT_FAST8_MAX__", "__INT_FAST16_MAX__", "__INT_FAST32_MAX__", "__INT_FAST64_MAX__", "__UINT_FAST8_MAX__", "__UINT_FAST16_MAX__", "__UINT_FAST32_MAX__", "__UINT_FAST64_MAX__", "__INTPTR_MAX__", "__UINTPTR_MAX__", "__WCHAR_MIN__", "__WINT_MIN__", "__SIG_ATOMIC_MIN__", "__SCHAR_WIDTH__", "__SHRT_WIDTH__", "__INT_WIDTH__", "__LONG_WIDTH__", "__LONG_LONG_WIDTH__", "__PTRDIFF_WIDTH__", "__SIG_ATOMIC_WIDTH__", "__SIZE_WIDTH__", "__WCHAR_WIDTH__", "__WINT_WIDTH__", "__INT_LEAST8_WIDTH__", "__INT_LEAST16_WIDTH__", "__INT_LEAST32_WIDTH__", "__INT_LEAST64_WIDTH__", "__INT_FAST8_WIDTH__", "__INT_FAST16_WIDTH__", "__INT_FAST32_WIDTH__", "__INT_FAST64_WIDTH__", "__INTPTR_WIDTH__", "__INTMAX_WIDTH__", "__SIZEOF_INT__", "__SIZEOF_INTMAX__", "__SIZEOF_UINTMAX__", "__SIZEOF_LONG__", "__SIZEOF_LONG_LONG__", "__SIZEOF_SHORT__", "__SIZEOF_POINTER__", "__SIZEOF_FLOAT__", "__SIZEOF_DOUBLE__", "__SIZEOF_LONG_DOUBLE__", "__SIZEOF_SIZE_T__", "__SIZEOF_WCHAR_T__", "__SIZEOF_WINT_T__", "__SIZEOF_PTRDIFF_T__", "__TIMESTAMP__", "__BASE_FILE__", "__CHAR_BIT__", "__FUNCTION__", "__GNUC_MINOR__", "__GNUC_PATCHLEVEL__", "__GNUC__", "__GNUG__", "__INCLUDE_LEVEL__", "__INTMAX_MAX__", "__INT_MAX__", "__LONG_LONG_MAX__", "__LONG_MAX__", "__SCHAR_MAX__", "__SHRT_MAX__", "__DBL_MIN__", "__DBL_MAX__", "__FLT_MIN__", "__FLT_MAX__", "__WCHAR_MAX__", "__WCHAR_UNSIGNED__", "__AES__", "__AVX__", "__AVX2__", "__ABM__", "__BMI__", "__BMI2__", "__FMA__", "__ADX__", "__PCLMUL__", "__POPCNT__", "__RDRND__", "__RDSEED__", "__SHA__", "__SSE__", "__SSE2__", "__SSE3__", "__SSSE3__", "__SSE4_1__", "__SSE4_2__", "__XSAVE__", "__CLFLUSHOPT__", "__RDPID__", "__STDC_IEC_559__", "__FILE__", "__LINE__", "__DATE__", } }, -- { Id=3, -- List= { -- "typedef", "inline", "auto", "class", "explicit", "extern", "friend", "inline", "mutable", "operator", -- "register", "template", "private", "protected", "public", "typeid", "virtual", "volatile", "constexpr", "nullptr", "decltype" -- } -- }, -- { Id=3, -- Regex=[[(\w+)\s*\:\:]] -- }, -- { Id=4, -- Regex=[[(\w+)\s*\(]] -- } } Strings = { Delimiter=[["|']], RawPrefix="R", Escape=[=[\\[abtnvfre\\\?'"]|\\\d{1,3}|\\x[[:xdigit:]]{2}]=], } Comments = { { Block=true, Nested=false, Delimiter = { [[\/\*]], [[\*\/]] } }, { Block=false, Delimiter = { [[//]] } } } IgnoreCase=false PreProcessor = { Prefix=[[#]], Continuation="\\", } Operators=[[\(|\)|\[|\]|\{|\}|\,|\;|\.|\:|\&|<|>|\!|=|\/|\*|\%|\+|\-|\~|\||\^|\?]] EnableIndentation=true -- resolve issue with C++14 number separator syntax function OnStateChange(oldState, newState, token) if token=="'" and oldState==HL_NUMBER and newState==HL_STRING then return HL_NUMBER end return newState end
46,056
1,973
jart/cosmopolitan
false
cosmopolitan/tool/emacs/cosmo-platform-constants.el
(defconst cosmo-platform-constants-regex (let ( (gcc412 '("__cplusplus" "__OBJC__" "__STRICT_ANSI__" "__ELF__" "__VERSION__" "__OPTIMIZE__" "__OPTIMIZE_SIZE__" "__NO_INLINE__" "__CHAR_UNSIGNED__" "__WCHAR_UNSIGNED__" "__REGISTER_PREFIX__" "__USER_LABEL_PREFIX__" "__SIZE_TYPE__" "__PTRDIFF_TYPE__" "__WCHAR_TYPE__" "__CHAR16_TYPE__" "__CHAR32_TYPE__" "__WINT_TYPE__" "__INTMAX_TYPE__" "__DEPRECATED" "__EXCEPTIONS" "__USING_SJLJ_EXCEPTIONS__" "__GXX_WEAK__" "__NEXT_RUNTIME__" "__LP64__" "__SSP__" "__SSP_ALL__" "__unix__" "__vax__" "__ns16000__" "__pic__" "__pie__" "__PIC__" "__PIE__" "__ASSEMBLER__" "__code_model_large__" "__code_model_medium__")) (cpp92 '("__SEG_FS" "__SEG_GS" "__BYTE_ORDER__" "__ORDER_LITTLE_ENDIAN__" "__ORDER_BIG_ENDIAN__" "__ORDER_PDP_ENDIAN__" "__FLOAT_WORD_ORDER__" "__GFORTRAN__" "__GCC_ASM_FLAG_OUTPUTS__" "__GNUC_GNU_INLINE__" "__GNUC_STDC_INLINE__" "__GXX_RTTI" "__GXX_EXPERIMENTAL_CXX0X__" "__SSP_STRONG__" "__SSP_EXPLICIT__" "__SANITIZE_ADDRESS__" "__SANITIZE_THREAD__" "__SANITIZE_MEMORY__" "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1" "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2" "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4" "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8" "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16" "__HAVE_SPECULATION_SAFE_VALUE" "__GCC_HAVE_DWARF2_CFI_ASM" "__STDC_WANT_IEC_60559_TYPES_EXT__" "__GCC_IEC_559" "__SUPPORT_SNAN__" "__GCC_IEC_559_COMPLEX" "__NO_MATH_ERRNO__" "__gnu__")) (cosmo '("__LINKER__")) ) (concat "\\_<" (regexp-opt (append cpp92 gcc412 cosmo)) "\\_>"))) (provide 'cosmo-platform-constants)
2,348
85
jart/cosmopolitan
false
cosmopolitan/tool/emacs/ld-script.el
;;; ld-script.el --- GNU linker script editing mode for Emacs ;; Copyright (C) 2001-2018 Free Software Foundation, Inc. ;; Author: Masatake YAMATO<[email protected]> ;; Keywords: languages, faces ;; This file is part of GNU Emacs. ;; GNU Emacs is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; GNU Emacs is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. ;;; Commentary: ;; Major mode for editing GNU linker (ld) scripts. ;;; Code: ;; Custom (defgroup ld-script nil "GNU linker script code editing commands for Emacs." :prefix "ld-script-" :group 'languages) (defvar ld-script-location-counter-face 'ld-script-location-counter) (defface ld-script-location-counter '((t :weight bold :inherit font-lock-builtin-face)) "Face for location counter in GNU ld script." :group 'ld-script) ;; Syntax rules (defvar ld-script-mode-syntax-table (let ((st (make-syntax-table))) (modify-syntax-entry ?\ "-" st) (modify-syntax-entry ?{ "(}" st) (modify-syntax-entry ?} "){" st) (modify-syntax-entry ?\( "()" st) (modify-syntax-entry ?\) ")(" st) (modify-syntax-entry ?\[ "(]" st) (modify-syntax-entry ?\] ")[" st) (modify-syntax-entry ?_ "_" st) (modify-syntax-entry ?. "_" st) (modify-syntax-entry ?\\ "\\" st) (modify-syntax-entry ?: "." st) (modify-syntax-entry ?, "." st) (modify-syntax-entry ?? "." st) (modify-syntax-entry ?= "." st) (modify-syntax-entry ?* ". 23" st) (modify-syntax-entry ?/ ". 14" st) (modify-syntax-entry ?+ "." st) (modify-syntax-entry ?- "." st) (modify-syntax-entry ?! "." st) (modify-syntax-entry ?~ "." st) (modify-syntax-entry ?% "." st) (modify-syntax-entry ?< "." st) (modify-syntax-entry ?> "." st) (modify-syntax-entry ?& "." st) (modify-syntax-entry ?| "." st) (modify-syntax-entry ?\" "\"" st) st) "Syntax table used while in `ld-script-mode'.") ;; Font lock keywords ;; (The section number comes from ld's info.) (defvar ld-script-keywords '( ;; 3.4.1 Setting the Entry Point "ENTRY" ;; 3.4.2 Commands Dealing with Files "INCLUDE" "INPUT" "GROUP" "AS_NEEDED" "OUTPUT" "SEARCH_DIR" "STARTUP" ;; 3.4.3 Commands Dealing with Object File Formats "OUTPUT_FORMAT" "TARGET" ;; 3.4.4 Assign alias names to memory regions "REGION_ALIAS" ;; 3.4.5 Other Linker Script Commands "ASSERT" "EXTERN" "FORCE_COMMON_ALLOCATION" "INHIBIT_COMMON_ALLOCATION" "INSERT" "AFTER" "BEFORE" "NOCROSSREFS" "NOCROSSREFS_TO" "OUTPUT_ARCH" "LD_FEATURE" ;; 3.5.2 HIDDEN "HIDDEN" ;; 3.5.3 PROVIDE "PROVIDE" ;; 3.5.4 PROVIDE_HIDDEN "PROVIDE_HIDDEN" ;; 3.6 SECTIONS Command "SECTIONS" ;; 3.6.4.2 Input Section Wildcard Patterns "SORT" "SORT_NONE" "SORT_BY_NAME" "SORT_BY_ALIGNMENT" "SORT_BY_INIT_PRIORITY" ;; 3.6.4.3 Input Section for Common Symbols "COMMON" ;; 3.6.4.4 Input Section and Garbage Collection "KEEP" ;; 3.6.5 Output Section Data "BYTE" "SHORT" "LONG" "QUAD" "SQUAD" "FILL" ;; 3.6.6 Output Section Keywords "CREATE_OBJECT_SYMBOLS" "CONSTRUCTORS" "__CTOR_LIST__" "__CTOR_END__" "__DTOR_LIST__" "__DTOR_END__" ;; 3.6.7 Output Section Discarding ;; See `ld-script-font-lock-keywords' ;; 3.6.8.1 Output Section Type "NOLOAD" "DSECT" "COPY" "INFO" "OVERLAY" ;; 3.6.8.2 Output Section LMA "AT" ;; 3.6.8.4 Forced Input Alignment "SUBALIGN" ;; 3.6.8.5 Output Section Constraint "ONLY_IF_RO" "ONLY_IF_RW" ;; 3.6.8.7 Output Section Phdr ":PHDR" ;; 3.7 MEMORY Command "MEMORY" ;; 3.8 PHDRS Command "PHDRS" "FILEHDR" "FLAGS" "PT_NULL" "PT_LOAD" "PT_DYNAMIC" "PT_INTERP" "PT_NOTE" "PT_SHLIB" "PT_PHDR" "PT_GNU_STACK" "PT_TLS" ;; 3.9 VERSION Command "VERSION") "Keywords used of GNU ld script.") ;; 3.10.2 Symbolic Constants ;; 3.10.9 Builtin Functions (defvar ld-script-builtins '("CONSTANT" "MAXPAGESIZE" "COMMONPAGESIZE" "ABSOLUTE" "ADDR" "ALIGN" "ALIGNOF" "BLOCK" "DATA_SEGMENT_ALIGN" "DATA_SEGMENT_END" "DATA_SEGMENT_RELRO_END" "DEFINED" "LENGTH" "len" "l" "LOADADDR" "LOG2CEIL" "MAX" "MIN" "NEXT" "ORIGIN" "org" "o" "SEGMENT_START" "SIZEOF" "SIZEOF_HEADERS" "sizeof_headers") "Builtin functions of GNU ld script.") (defvar ld-script-font-lock-keywords (append `((,(concat "\\_<" (regexp-opt ld-script-keywords) "\\_>") 0 font-lock-keyword-face) (,(concat "\\_<" (regexp-opt ld-script-builtins) "\\_>") 0 font-lock-builtin-face) ;; 3.6.7 Output Section Discarding ;; 3.6.4.1 Input Section Basics ;; 3.6.8.7 Output Section Phdr ("/DISCARD/\\|EXCLUDE_FILE\\|:NONE" . font-lock-warning-face) ("\\W\\(\\.\\)\\W" 1 ld-script-location-counter-face) ) cpp-font-lock-keywords) "Default font-lock-keywords for `ld-script-mode'.") ;;;###autoload (define-derived-mode ld-script-mode prog-mode "LD-Script" "A major mode to edit GNU ld script files" (set (make-local-variable 'comment-start) "/* ") (set (make-local-variable 'comment-end) " */") (set (make-local-variable 'font-lock-defaults) '(ld-script-font-lock-keywords nil))) (provide 'ld-script) ;;; ld-script.el ends here
5,792
186
jart/cosmopolitan
false
cosmopolitan/tool/emacs/optinfo-mode.el
(require 'compile) (define-derived-mode optinfo-mode compilation-mode "Optimization Info" (let ((root (locate-dominating-file (buffer-file-name) "Makefile"))) (when root (setq-local default-directory root)))) (auto-compression-mode t) (add-to-list 'auto-mode-alist '("\\.optinfo\\(\\|\\.gz\\)$" . optinfo-mode)) (provide 'optinfo-mode)
351
12
jart/cosmopolitan
false
cosmopolitan/tool/hello/hello.c
#include "libc/calls/calls.h" #include "libc/str/str.h" // hello world with minimal build system dependencies static ssize_t Write(int fd, const char *s) { return write(fd, s, strlen(s)); } int main(int argc, char *argv[]) { Write(1, "hello\n"); }
255
13
jart/cosmopolitan
false
cosmopolitan/tool/hello/hello.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_HELLO TOOL_HELLO_SRCS := $(wildcard tool/hello/*.c) TOOL_HELLO_OBJS = $(TOOL_HELLO_SRCS:%.c=o/$(MODE)/%.o) TOOL_HELLO_COMS = $(TOOL_HELLO_SRCS:%.c=o/$(MODE)/%.com) TOOL_HELLO_BINS = $(TOOL_HELLO_COMS) $(TOOL_HELLO_COMS:%=%.dbg) TOOL_HELLO_DIRECTDEPS = \ LIBC_CALLS \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STR \ LIBC_SYSV \ LIBC_STUBS TOOL_HELLO_DEPS := \ $(call uniq,$(foreach x,$(TOOL_HELLO_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/hello/hello.pkg: \ $(TOOL_HELLO_OBJS) \ $(foreach x,$(TOOL_HELLO_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/hello/%.com.dbg: \ $(TOOL_HELLO_DEPS) \ o/$(MODE)/tool/hello/%.o \ o/$(MODE)/tool/hello/hello.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) $(TOOL_HELLO_OBJS): \ $(BUILD_FILES) \ tool/hello/hello.mk .PHONY: o/$(MODE)/tool/hello o/$(MODE)/tool/hello: $(TOOL_HELLO_BINS) $(TOOL_HELLO_CHECKS)
1,128
41
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lambda.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/calls/calls.h" #include "libc/calls/struct/rlimit.h" #include "libc/calls/struct/sigaction.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/rlimit.h" #include "libc/sysv/consts/sig.h" #include "third_party/getopt/getopt.h" #include "tool/lambda/lib/blc.h" #define USAGE \ " [-?hubBdsarvnNlS] <stdin >expr.txt\n\ Binary Lambda Calculus Virtual Machine\n\ \n\ FLAGS\n\ \n\ -h help\n\ -r rex log\n\ -b binary 8-bit i/o\n\ -B debug print binary\n\ -l print lambda notation\n\ -a action log [implies -r]\n\ -v variable log [implies -r]\n\ -s full machine state logging\n\ -n disables name rewriting rules\n\ -N disables most unicode symbolism\n\ -d dump terms on successful exit\n" #define NIL 23 #define TRUE 27 #define FALSE 23 #define REF(c) (++(c)->refs, c) static const char kRom[] = { APP, 0, // 0 (λ 0 λ 0 (λ 0 wr0 wr1) put) (main gro) ABS, // 2 λ 0 λ 0 (λ 0 wr0 wr1) put APP, 0, // 3 VAR, 0, // 5 ABS, // 7 APP, // 8 ABS, // 9 λ 0 λ 0 wr0 wr1 APP, 2, // 10 VAR, // 12 IOP, // 13 ABS, // 14 λ 0 wr0 wr1 APP, 4, // 15 APP, 1, // 17 VAR, // 19 IOP, // 20 wr0 IOP, 0, // 21 wr1 ABS, // 23 (λλ 0) a.k.a. nil ABS, // 24 exit VAR, // 25 0, // 26 exit[0] ABS, // 27 (λλ 1) a.k.a. true ABS, // 28 VAR, 1, // 29 }; static int postdump; static int kLazy[256]; void Quit(int sig) { Dump(0, end, stderr); exit(128 + sig); } void PrintUsage(const char *prog, int rc, FILE *f) { fputs("Usage: ", f); fputs(prog, f); fputs(USAGE, f); exit(rc); } int Backref(int x) { return x - (end + 1); } static inline void Expand(int c) { if (end >= TERMS) Error(5, "OUT OF TERMS"); mem[end++] = c; } void Gc(struct Closure *p) { struct Closure *t; while (p && p != &root) { if (--p->refs) break; Gc(p->next); t = p->envp; p->envp = 0; p->next = frep; frep = p; p = t; } } void Var(void) { int i, x; struct Closure *t, *e; e = t = envp; x = mem[ip + 1]; for (i = 0; i < x && e != &root; ++i) e = e->next; if (e == &root) Error(10 + x, "UNDEFINED VARIABLE %d", x); ip = e->term; envp = REF(e->envp); Gc(t); } void Gro(void) { int c = fgetc(stdin); if (c != -1) { Expand(ABS); Expand(APP); Expand(4); Expand(APP); Expand(Backref(binary ? kLazy[c] : c & 1 ? FALSE : TRUE)); Expand(VAR); Expand(0); } else { Expand(ABS); Expand(ABS); Expand(VAR); Expand(0); } } void Put(void) { int bit; long newip; if (!binary) { co = '0' + (ip & 1); fputc(co, stdout); newip = 2; } else if (mem[ip + 1] & 1) { // ip ∈ {6,13} fputc(co, stdout); newip = 2; } else { // ip ∈ {20,21} newip = 9; // (λ 0 (λ 0 wr1 wr0)) bit = ip & 1; co = (co * 2) | bit; } if (ferror(stdout)) { exit(55); } ip = newip; } void Bye(void) { int rc = mem[ip + 2]; // (λ 0) [exitcode] if (rc) Error(rc, "CONTINUATIONS EXHAUSTED"); if (postdump && !rc) Dump(0, end, stderr); exit(0); } // pops continuation and pushes it to environment void Abs(void) { if (!contp) Bye(); struct Closure *t = contp; contp = t->next; t->next = envp; envp = t; ++ip; } struct Closure *Alloc(void) { struct Closure *t; if (!(t = frep)) { if (!(t = Calloc(1, sizeof(struct Closure)))) { Error(6, "OUT OF HEAP"); } } frep = t->next; t->refs = 1; ++heap; return t; } // pushes continuation for argument void App(void) { int x = mem[ip + 1]; struct Closure *t = Alloc(); t->term = ip + 2 + x; t->envp = t->term > 21 && t->term != end ? REF(envp) : &root; t->next = contp; contp = t; ip += 2; } int LoadByte(int c) { int i, r = end; for (i = 7; i >= 0; --i) { Expand(ABS); Expand(APP); Expand(i ? +4 : Backref(NIL)); Expand(APP); Expand(Backref(c & (1 << i) ? FALSE : TRUE)); Expand(VAR); Expand(0); } return r; } void LoadRom(void) { long i; for (; end < sizeof(kRom) / sizeof(*kRom); ++end) { mem[end] = kRom[end]; } mem[4] = binary ? 2 : 9; if (binary) { for (i = 0; i < 256; ++i) { kLazy[i] = LoadByte(i); } } mem[1] = end - 2; } void Iop(void) { if (ip == end) { Gro(); } else { Put(); // ip ∈ {6,13,20,21} } Gc(envp); envp = &root; } static void Rex(void) { if (slog) PrintMachineState(stderr); if (rlog && (alog || mem[ip] != APP)) { PrintExpressions(stderr, alog, vlog); } switch (mem[ip]) { case VAR: Var(); break; case APP: App(); break; case ABS: Abs(); break; case IOP: Iop(); break; default: Error(7, "CORRUPT TERM"); } } void Krivine(void) { int main; long gotoget; LoadRom(); mem[end++] = APP; gotoget = end++; main = end; mem[gotoget] = Parse(1, stdin).n; if (rlog) { Print(main, 1, 0, stderr); fputs("\n", stderr); if (alog) { fputs("⟿ wrap[", stderr); Print(0, 1, 0, stderr); fputs("]\n", stderr); } } for (;;) Rex(); } void LoadFlags(int argc, char *argv[]) { int i; const char *prog; prog = argc ? argv[0] : "cblc"; while ((i = getopt(argc, argv, "?hubBdsarvnNlS")) != -1) { switch (i) { case 'b': binary = 1; break; case 'S': safer = 1; break; case 'n': noname = 1; break; case 'N': asciiname = 1; break; case 'B': style = 2; break; case 'l': style = 1; break; case 's': slog = 1; break; case 'r': rlog = 1; break; case 'a': rlog = 1; alog = 1; break; case 'v': rlog = 1; vlog = 1; break; case 'd': postdump = 1; break; case '?': case 'h': PrintUsage(prog, 0, stdout); default: PrintUsage(prog, 1, stderr); } } } int main(int argc, char *argv[]) { struct rlimit rlim = {512 * 1024 * 1024, 512 * 1024 * 1024}; setrlimit(RLIMIT_AS, &rlim); signal(SIGQUIT, Quit); signal(SIGPIPE, Quit); LoadFlags(argc, argv); setlocale(LC_ALL, ""); setvbuf(stdout, 0, _IOLBF, 0); setvbuf(stderr, 0, _IOLBF, 0); Krivine(); }
8,476
355
jart/cosmopolitan
false
cosmopolitan/tool/lambda/tromp.c
// Public Domain // Author: John Tromp // Source: IOCCC 2012 #include "libc/runtime/runtime.h" #include "tool/lambda/lib/blc.h" #define A 500000 #define X 8 #define Int long // clang-format off Int L[A],m,b,*D=A, *c,*a=L,C,*U=L,u;s (_){u--&&s(a=*a);} char*B,I,O;S(){b=b --?b:m|read(0,&I,1 )-1;return~I>>b&1; }k(l,u){for(;l<=u; U-L<A?*U++=46^l++[ "-,&,,/.--/,:-,'/" ".-,-,,/.-,*,//..," ]:exit(5));}p(Int*m){ return!*U?*m=S()?U++,!S ()?m[1]=p(++U),2:3:1,p(U) :S()?U+=2:p(U[1]++),U-m;}x( c){k(7*!b,9);*U++=b&&S();c&&x (b);}d(Int*l){--l[1]||d(l[d(*l), *l=B,B=l,2]);}main(e){for(k(10,33 ),a[4]-=m=e-2&7,a[23]=p(U),b=0;;e-2 ?e?e-3?s(D=a),C=a [3],++1[a=a[2]],d( D):c?D=c,c=*D,*D= a,a=D:exit(L[C+1]) :C--<23?C=u+m&1?O =O+O|C&1,9:write(m ||(O=C+28),&O,1)+ 1:(S(),x(0<b++?k(0, 6),U[-5]=96:0)):( D=B?B:Calloc(4,X)) ?B=*D,*D=c,c=D,D[ 2]=a,a[++D[1]]++,D [3]=++C+u:exit(6) )e=L[C++],u=L[C];}
1,153
38
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lambda.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_LAMBDA TOOL_LAMBDA_SRCS := $(wildcard tool/lambda/*.c) TOOL_LAMBDA_OBJS = \ $(TOOL_LAMBDA_SRCS:%.c=o/$(MODE)/%.o) TOOL_LAMBDA_COMS := \ $(TOOL_LAMBDA_SRCS:%.c=o/$(MODE)/%.com) TOOL_LAMBDA_BINS = \ $(TOOL_LAMBDA_COMS) \ $(TOOL_LAMBDA_COMS:%=%.dbg) TOOL_LAMBDA_DIRECTDEPS = \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_CALLS \ LIBC_RUNTIME \ LIBC_FMT \ LIBC_STR \ LIBC_SYSV \ LIBC_STDIO \ LIBC_X \ LIBC_STUBS \ LIBC_NEXGEN32E \ TOOL_LAMBDA_LIB \ THIRD_PARTY_GETOPT TOOL_LAMBDA_DEPS := \ $(call uniq,$(foreach x,$(TOOL_LAMBDA_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/lambda/lambda.pkg: \ $(TOOL_LAMBDA_OBJS) \ $(foreach x,$(TOOL_LAMBDA_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/lambda/%.com.dbg: \ $(TOOL_LAMBDA_DEPS) \ o/$(MODE)/tool/lambda/%.o \ o/$(MODE)/tool/lambda/lambda.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/lambda/tromp.o: private \ OVERRIDE_CFLAGS += \ -w $(TOOL_LAMBDA_OBJS): \ $(BUILD_FILES) \ tool/lambda/lambda.mk .PHONY: o/$(MODE)/tool/lambda o/$(MODE)/tool/lambda: $(TOOL_LAMBDA_BINS) $(TOOL_LAMBDA_CHECKS)
1,436
59
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lam2bin.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/intrin/kprintf.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/str/str.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [-?h] <lambda.txt >binary.txt\n\ Converts lambda notation to ASCII binary, e.g.\n\ \n\ $ printf 'λf.(λx.f(xx))(λx.f(xx))' | lam2bin\n\ 000100011100110100001110011010\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -? Help\n" struct Node { int t, x; struct Node *l, *r; }; int sp; int end; int unget; int args[1024]; const char *str; static void LoadFlags(int argc, char *argv[]) { int i; const char *prog; prog = argc ? argv[0] : "lam2bin"; while ((i = getopt(argc, argv, "?h")) != -1) { switch (i) { case '?': case 'h': fputs("Usage: ", stdout); fputs(prog, stdout); fputs(USAGE, stdout); exit(0); default: fputs("Usage: ", stderr); fputs(prog, stderr); fputs(USAGE, stderr); exit(1); } } } wontreturn static void Error(int rc, const char *s, ...) { va_list va; fflush(stdout); fputs("\33[1;31merror\33[37m: ", stderr); fflush(stderr); va_start(va, s); kvprintf(s, va); va_end(va); fputc('\n', stderr); exit(rc); } static struct Node *NewNode(int t, int x, struct Node *l, struct Node *r) { struct Node *n; n = malloc(sizeof(struct Node)); n->t = t; n->x = x; n->l = l; n->r = r; return n; } static int Greed(void) { int c, t; for (t = 0;;) { if (unget) { c = unget; unget = 0; } else if (str) { if (*str) { c = *str++; } else { str = 0; c = fgetwc(stdin); } } else { c = fgetwc(stdin); } if (c == EOF) return c; if (!t) { if (c == '#' || c == ';') { t = 1; continue; } } else { if (c == '\n') { t = 0; } continue; } if (iswspace(c)) continue; if (!str) { switch (c) { case L'⊥': str = "(\\ab.b)"; continue; case L'⊤': str = "(\\ab.a)"; continue; #if 0 case L'0': str = "(\\ab.b)"; continue; case L'1': str = "(\\ab.ab)"; continue; case L'2': str = "(\\ab.a(ab))"; continue; case L'3': str = "(\\ab.a(a(ab)))"; continue; case L'4': str = "(\\ab.a(a(a(ab))))"; continue; case L'5': str = "(\\ab.a(a(a(a(ab)))))"; continue; case L'6': str = "(\\ab.a(a(a(a(a(ab))))))"; continue; case L'7': str = "(\\ab.a(a(a(a(a(a(ab)))))))"; continue; case L'8': str = "(\\ab.a(a(a(a(a(a(a(ab))))))))"; continue; case L'9': str = "(\\ab.a(a(a(a(a(a(a(a(ab)))))))))"; continue; #endif case L'ω': str = "(\\x.xx)"; continue; case L'Ω': str = "((\\x.xx)(\\x.xx))"; continue; case L'Y': str = "(\\f.(\\x.f(xx))(\\x.f(xx)))"; continue; case L'∧': str = "(\\ab.aba)"; continue; case L'∨': str = "(\\ab.aab)"; continue; case L'⊻': str = "(\\ab.a((\\c.c(\\de.e)(\\de.d))b)b)"; continue; case L'¬': str = "(\\a.a(\\bc.c)(\\bc.b))"; continue; case L'+': str = "(\\abcd.ac(bcd))"; continue; case L'*': str = "(\\abc.a(bc))"; continue; case L'^': str = "(\\ab.ba)"; continue; case L'-': str = "(\\ab.b(\\cde.c(\\fg.g(fd))(\\f.e)(\\f.f))a)"; continue; case L'/': str = "(\\a.(\\b.(\\c.cc)(\\c.b(cc)))(\\bcdef.(\\g.(\\h.h(\\ijk.k)(" "\\ij.i))g((\\hi.i)ef)(e(bgdef)))((\\gh.h(\\ijk.i(\\lm.m(lj))(" "\\l.k)(\\l.l))g)cd))((\\bcd.c(bcd))a))"; continue; case L'Я': str = "(\\a.a((\\b.bb)(\\bcde.d(bb)(\\f.fce)))(\\bc.c))"; continue; default: break; } } return c; } } static int Need(void) { int c; if ((c = Greed()) != EOF) return c; Error(1, "unfinished expression"); } static struct Node *Parse1(void) { wint_t c; int i, oldsp; struct Node *r, *p, *q, *s; if ((c = Greed()) == EOF) return 0; if (c == L'λ' || c == '\\') { oldsp = sp; c = Need(); if (!(isalnum(c) || c == '_')) Error(2, "lambda needs argument"); p = r = NewNode(0, 0, 0, 0); args[sp++] = c; while ((c = Need()) != '.') { if (!(isalnum(c) || c == '_')) Error(3, "lambda needs argument"); p = p->l = NewNode(0, 0, 0, 0); args[sp++] = c; } q = Parse1(); if (!q) Error(4, "lambda needs body"); p->l = q; while ((q = Parse1())) { p->l = NewNode(2, 0, p->l, q); } sp = oldsp; return r; } else if (c == L'!') { // intentionally trigger undefined variable return NewNode(1, sp, 0, 0); } else if (isalnum(c) || c == '_') { for (i = sp; i--;) { if (args[i] == c) { i = sp - 1 - i; break; } } if (i < 0) Error(5, "undefined variable: %d %lc", c, c); return NewNode(1, i, 0, 0); } else if (c == '(') { p = r = Parse1(); if (!p) Error(6, "empty parenthesis"); while ((q = Parse1())) { r = NewNode(2, 0, r, q); } c = Need(); if (c != ')') Error(7, "expected closing parenthesis"); return r; } else if (c == ')') { unget = c; return 0; } else { Error(8, "unexpected character: 0x%04x %lc", c, c); } } static struct Node *Parse(void) { wint_t c; int i, oldsp; struct Node *r, *p, *q, *s; p = r = Parse1(); if (!p) Error(6, "empty expression"); while ((q = Parse1())) { r = NewNode(2, 0, r, q); } return r; } static void Print(struct Node *p) { int i; if (p->t == 0) { fputc('0', stdout); fputc('0', stdout); Print(p->l); } else if (p->t == 1) { for (i = -1; i < p->x; ++i) { fputc('1', stdout); } fputc('0', stdout); } else if (p->t == 2) { fputc('0', stdout); fputc('1', stdout); Print(p->l); Print(p->r); } else { abort(); } } int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); LoadFlags(argc, argv); Print(Parse()); }
8,343
309
jart/cosmopolitan
false
cosmopolitan/tool/lambda/bru2bin.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/intrin/kprintf.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/str/str.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [-?h01] <lambda.txt >binary.txt\n\ Converts de Bruijn notation to ASCII binary, e.g.\n\ \n\ $ printf 'λ (λ 1 (0 0)) (λ 1 (0 0)))' | lam2bin\n\ 000100011100110100001110011010\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -? Help\n\ -0 0-based indexing\n\ -1 1-based indexing\n" struct Node { int t, x; struct Node *l, *r; }; int sp; int end; int unget; int indexing; const char *str; static void LoadFlags(int argc, char *argv[]) { int i; const char *prog; prog = argc ? argv[0] : "lam2bin"; while ((i = getopt(argc, argv, "?h01")) != -1) { switch (i) { case '0': indexing = 0; break; case '1': indexing = 1; break; case '?': case 'h': fputs("Usage: ", stdout); fputs(prog, stdout); fputs(USAGE, stdout); exit(0); default: fputs("Usage: ", stderr); fputs(prog, stderr); fputs(USAGE, stderr); exit(1); } } } wontreturn static void Error(int rc, const char *s, ...) { va_list va; fflush(stdout); fputs("\33[1;31merror\33[37m: ", stderr); fflush(stderr); va_start(va, s); kvprintf(s, va); va_end(va); fputc('\n', stderr); exit(rc); } static struct Node *NewNode(int t, int x, struct Node *l, struct Node *r) { struct Node *n; n = malloc(sizeof(struct Node)); n->t = t; n->x = x; n->l = l; n->r = r; return n; } static int Greed(void) { int c, t; for (t = 0;;) { if (unget) { c = unget; unget = 0; } else if (str) { if (*str) { c = *str++; } else { str = 0; c = fgetwc(stdin); } } else { c = fgetwc(stdin); } if (c == EOF) return c; if (!t) { if (c == '#' || c == ';') { t = 1; continue; } } else { if (c == '\n') { t = 0; } continue; } if (!str) { switch (c) { case L'⊥': str = "(\\ab.b)"; continue; case L'⊤': str = "(\\ab.a)"; continue; #if 0 case L'0': str = "(\\ab.b)"; continue; case L'1': str = "(\\ab.ab)"; continue; case L'2': str = "(\\ab.a(ab))"; continue; case L'3': str = "(\\ab.a(a(ab)))"; continue; case L'4': str = "(\\ab.a(a(a(ab))))"; continue; case L'5': str = "(\\ab.a(a(a(a(ab)))))"; continue; case L'6': str = "(\\ab.a(a(a(a(a(ab))))))"; continue; case L'7': str = "(\\ab.a(a(a(a(a(a(ab)))))))"; continue; case L'8': str = "(\\ab.a(a(a(a(a(a(a(ab))))))))"; continue; case L'9': str = "(\\ab.a(a(a(a(a(a(a(a(ab)))))))))"; continue; #endif case L'ω': str = "(\\x.xx)"; continue; case L'Ω': str = "((\\x.xx)(\\x.xx))"; continue; case L'Y': str = "(\\f.(\\x.f(xx))(\\x.f(xx)))"; continue; case L'∧': str = "(\\ab.aba)"; continue; case L'∨': str = "(\\ab.aab)"; continue; case L'⊻': str = "(\\ab.a((\\c.c(\\de.e)(\\de.d))b)b)"; continue; case L'¬': str = "(\\a.a(\\bc.c)(\\bc.b))"; continue; case L'+': str = "(\\abcd.ac(bcd))"; continue; case L'*': str = "(\\abc.a(bc))"; continue; case L'^': str = "(\\ab.ba)"; continue; case L'-': str = "(\\ab.b(\\cde.c(\\fg.g(fd))(\\f.e)(\\f.f))a)"; continue; case L'/': str = "(\\a.(\\b.(\\c.cc)(\\c.b(cc)))(\\bcdef.(\\g.(\\h.h(\\ijk.k)(" "\\ij.i))g((\\hi.i)ef)(e(bgdef)))((\\gh.h(\\ijk.i(\\lm.m(lj))(" "\\l.k)(\\l.l))g)cd))((\\bcd.c(bcd))a))"; continue; case L'Я': str = "(\\a.a((\\b.bb)(\\bcde.d(bb)(\\f.fce)))(\\bc.c))"; continue; default: break; } } return c; } } static int Need(void) { int c; if ((c = Greed()) != EOF) return c; Error(1, "unfinished expression"); } static struct Node *Parse1(void) { wint_t c; int i, oldsp; struct Node *r, *p, *q, *s; do { if ((c = Greed()) == EOF) return 0; } while (iswspace(c)); if (c == L'λ' || c == '\\') { oldsp = sp; p = r = NewNode(0, 0, 0, 0); ++sp; for (;;) { c = Need(); if (c == L'λ' || c == '\\') { p = p->l = NewNode(0, 0, 0, 0); ++sp; continue; } else { unget = c; break; } } q = Parse1(); if (!q) Error(4, "lambda needs body"); p->l = q; while ((q = Parse1())) { p->l = NewNode(2, 0, p->l, q); } sp = oldsp; return r; } else if (c == L'!') { // intentionally trigger undefined variable return NewNode(1, sp, 0, 0); } else if (iswdigit(c)) { i = 0; for (;;) { i *= 10; i += c - '0'; c = Greed(); if (c == EOF) break; if (!iswdigit(c)) { unget = c; break; } } i -= indexing; if (i < 0) Error(5, "undefined variable: %lc", c); return NewNode(1, i, 0, 0); } else if (c == '(') { p = r = Parse1(); if (!p) Error(6, "empty parenthesis"); while ((q = Parse1())) { r = NewNode(2, 0, r, q); } c = Need(); if (c != ')') Error(7, "expected closing parenthesis"); return r; } else if (c == ')') { unget = c; return 0; } else { Error(8, "unexpected character: 0x%04x %lc", c, c); } } static struct Node *Parse(void) { wint_t c; int i, oldsp; struct Node *r, *p, *q, *s; p = r = Parse1(); if (!p) Error(6, "empty expression"); while ((q = Parse1())) { r = NewNode(2, 0, r, q); } return r; } static void Print(struct Node *p) { int i; if (p->t == 0) { fputc('0', stdout); fputc('0', stdout); Print(p->l); } else if (p->t == 1) { for (i = -1; i < p->x; ++i) { fputc('1', stdout); } fputc('0', stdout); } else if (p->t == 2) { fputc('0', stdout); fputc('1', stdout); Print(p->l); Print(p->r); } else { abort(); } } int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); LoadFlags(argc, argv); Print(Parse()); }
8,536
328
jart/cosmopolitan
false
cosmopolitan/tool/lambda/asc2bin.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 "third_party/getopt/getopt.h" #include "tool/lambda/lib/blc.h" #define USAGE \ " [-?h] [FILE...] <binary.txt >binary.bin\n\ Converts ASCII binary to ACTUAL binary, e.g.\n\ \n\ $ { printf 'λx.x' | o/lam2bin | o/asc2bin; printf abc; } | o/Blc\n\ abc\n\ \n\ $ printf '\n\ (00 (01 (01 10 ((01 (00 (01 10 10))\n\ (00000000 (01 (01 110 ((01 11110 11110)))\n\ (00 (01 (01 10 11110) 110)))))))\n\ (0000 10)))\n\ ' | asc2bin | xxd -b\n\ 00000000: 00010110 01000110 10000000 00010111 00111110 11110000 .F..>.\n\ 00000006: 10110111 10110000 01000000 ..@\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -? Help\n" void LoadFlags(int argc, char *argv[]) { int i; const char *prog; prog = argc ? argv[0] : "asc2bin"; while ((i = getopt(argc, argv, "?h")) != -1) { switch (i) { case '?': case 'h': fputs("Usage: ", stdout); fputs(prog, stdout); fputs(USAGE, stdout); exit(0); default: fputs("Usage: ", stderr); fputs(prog, stderr); fputs(USAGE, stderr); exit(1); } } } int main(int argc, char *argv[]) { int i, b, c, n; LoadFlags(argc, argv); n = c = i = 0; while ((b = GetBit(stdin)) != -1) { c |= b << (7 - n); if (++n == 8) { fputc(c, stdout); c = 0; n = 0; } } if (n) { fputc(c, stdout); } }
3,342
81
jart/cosmopolitan
false
cosmopolitan/tool/lambda/blcdump.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/rlimit.h" #include "libc/runtime/runtime.h" #include "libc/str/locale.h" #include "libc/sysv/consts/rlimit.h" #include "third_party/getopt/getopt.h" #include "tool/lambda/lib/blc.h" /** * @fileoverview Binary Lambda Calculus Dump Utility, e.g. * * $ echo 0000001110 | o//blcdump -b 2>/dev/null * (λ (λ (λ 2))) * * The term rom is printed to stderr along with all skewed overlapping * perspectives on the in-memory representation. * * $ echo 0000001110 | o//blcdump -b >/dev/null * .long ABS # 0=3: (λ (λ (λ 2))) * .long ABS # 1=3: (λ (λ 2)) * .long ABS # 2=3: (λ 2) * .long VAR # 3=1: 2 * .long 2 # 4=2: (⋯ ⋯) */ #define USAGE \ " [-?hbBnNlS] [FILE...] <stdin >expr.txt 2>memory.txt\n\ Binary Lambda Calculus Dump Tool\n\ \n\ FLAGS\n\ \n\ -h Help\n\ -b 8-bit binary mode\n\ -B debug print binary\n\ -l print lambda notation\n\ -n disables name rewriting rules\n\ -N disables most unicode symbolism\n" void PrintUsage(const char *prog, int rc, FILE *f) { fputs("Usage: ", f); fputs(prog, f); fputs(USAGE, f); exit(rc); } void LoadFlags(int argc, char *argv[]) { int i; const char *prog; prog = argc ? argv[0] : "blcdump"; while ((i = getopt(argc, argv, "?hubBnNlS")) != -1) { switch (i) { case 'b': binary = 1; break; case 'n': noname = 1; break; case 'N': asciiname = 1; break; case 'l': style = 1; break; case 'B': style = 2; break; case 'S': safer = 1; break; case '?': case 'h': PrintUsage(prog, 0, stdout); default: PrintUsage(prog, 1, stderr); } } } void Expand(int c) { if (end >= TERMS) Error(5, "OUT OF TERMS"); mem[end++] = c; } void ExpandBit(int b) { Expand(ABS); Expand(ABS); Expand(VAR); Expand(b); } void ExpandList(int next) { Expand(ABS); Expand(APP); Expand(next); Expand(APP); Expand(2); Expand(VAR); Expand(0); } void ExpandItem(int b) { ExpandList(8); ExpandBit(b); } void ExpandByte(int b) { ExpandList(4 + 8 * (7 + 4)); ExpandItem((b >> 0) & 1); ExpandItem((b >> 1) & 1); ExpandItem((b >> 2) & 1); ExpandItem((b >> 3) & 1); ExpandItem((b >> 4) & 1); ExpandItem((b >> 5) & 1); ExpandItem((b >> 6) & 1); ExpandItem((b >> 7) & 1); ExpandBit(0); } int main(int argc, char *argv[]) { struct Parse p; struct rlimit rlim = {512 * 1024 * 1024, 512 * 1024 * 1024}; setrlimit(RLIMIT_AS, &rlim); setlocale(LC_ALL, ""); setvbuf(stdout, 0, _IOFBF, 0); setvbuf(stderr, 0, _IOLBF, 0); LoadFlags(argc, argv); #if DEBUG logh = fopen("o//log", "w"); fprintf(logh, " IP END HEAP %-*s NOM MESSAGE\n", LOC, "LOC"); setvbuf(logh, 0, _IOLBF, 0); #endif end = 32; for (; !feof(stdin); ip = end) { p = Parse(1, stdin); if (p.n) { Print(p.i, 1, 0, stdout); fputc('\n', stdout); Dump(p.i, p.i + p.n, stderr); } } }
4,977
160
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/getbit.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/lambda/lib/blc.h" char GetBit(FILE* f) { wint_t c; char comment; static wint_t buf, mask; if (!binary) { for (comment = 0;;) { c = fgetwc(f); if (c == -1) break; if (!comment) { fflush(stdout); if (c == ';') { comment = 1; } else if (!iswspace(c) && c != '(' && c != ')' && c != '[' && c != ']') { if (c != -1) c &= 1; break; } } else if (c == '\n') { comment = 0; } } } else if (mask) { c = !!(buf & mask); mask >>= 1; } else { c = fgetc(f); if (c != -1) { buf = c; c = (c >> 7) & 1; mask = 64; } } return c; }
2,571
56
jart/cosmopolitan
false
cosmopolitan/tool/lambda/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───────────────────────┘ PKGS += TOOL_LAMBDA_LIB TOOL_LAMBDA_LIB_ARTIFACTS += TOOL_LAMBDA_LIB_A TOOL_LAMBDA_LIB = $(TOOL_LAMBDA_LIB_A_DEPS) $(TOOL_LAMBDA_LIB_A) TOOL_LAMBDA_LIB_A = o/$(MODE)/tool/lambda/lib/lambdalib.a TOOL_LAMBDA_LIB_A_FILES := $(filter-out %/.%,$(wildcard tool/lambda/lib/*)) TOOL_LAMBDA_LIB_A_HDRS = $(filter %.h,$(TOOL_LAMBDA_LIB_A_FILES)) TOOL_LAMBDA_LIB_A_SRCS_S = $(filter %.S,$(TOOL_LAMBDA_LIB_A_FILES)) TOOL_LAMBDA_LIB_A_SRCS_C = $(filter %.c,$(TOOL_LAMBDA_LIB_A_FILES)) TOOL_LAMBDA_LIB_A_CHECKS = \ $(TOOL_LAMBDA_LIB_A_HDRS:%=o/$(MODE)/%.ok) \ $(TOOL_LAMBDA_LIB_A).pkg TOOL_LAMBDA_LIB_A_SRCS = \ $(TOOL_LAMBDA_LIB_A_SRCS_S) \ $(TOOL_LAMBDA_LIB_A_SRCS_C) TOOL_LAMBDA_LIB_A_OBJS = \ $(TOOL_LAMBDA_LIB_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(TOOL_LAMBDA_LIB_A_SRCS_C:%.c=o/$(MODE)/%.o) TOOL_LAMBDA_LIB_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_INTRIN \ LIBC_LOG \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_MEM \ LIBC_FMT \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_GETOPT TOOL_LAMBDA_LIB_A_DEPS := \ $(call uniq,$(foreach x,$(TOOL_LAMBDA_LIB_A_DIRECTDEPS),$($(x)))) $(TOOL_LAMBDA_LIB_A): \ $(TOOL_LAMBDA_LIB_A).pkg \ $(TOOL_LAMBDA_LIB_A_OBJS) $(TOOL_LAMBDA_LIB_A).pkg: \ $(TOOL_LAMBDA_LIB_A_OBJS) \ $(foreach x,$(TOOL_LAMBDA_LIB_A_DIRECTDEPS),$($(x)_A).pkg) TOOL_LAMBDA_LIB_LIBS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x))) TOOL_LAMBDA_LIB_SRCS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_SRCS)) TOOL_LAMBDA_LIB_HDRS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_HDRS)) TOOL_LAMBDA_LIB_BINS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_BINS)) TOOL_LAMBDA_LIB_CHECKS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_CHECKS)) TOOL_LAMBDA_LIB_OBJS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_OBJS)) TOOL_LAMBDA_LIB_TESTS = $(foreach x,$(TOOL_LAMBDA_LIB_ARTIFACTS),$($(x)_TESTS)) .PHONY: o/$(MODE)/tool/lambda/lib o/$(MODE)/tool/lambda/lib: $(TOOL_LAMBDA_LIB_CHECKS)
2,245
63
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/debug.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/intrin/kprintf.h" #include "libc/str/str.h" #include "tool/lambda/lib/blc.h" const char *GetOpName(int x) { switch (x) { case VAR: return "var"; case APP: return "app"; case ABS: return "abs"; case IOP: return "iop"; default: return "wut"; } } int GetDepth(struct Closure *env) { int i; for (i = 0; env && env != &root; ++i) { env = env->next; } return i; } void PrintClosure(struct Closure *c, const char *name, int indent, FILE *f) { int i, j; char ibuf[21]; while (c && c != &root) { for (j = 0; j < indent; ++j) { if (j) { fputs("│ ", f); } else { fputs(" ", f); } } fputs(name, f); fputs(": ", f); Print(c->term, 0, GetDepth(c->envp), f); fputs(" +", f); FormatInt64(ibuf, c->refs); fputs(ibuf, f); fputc('\n', f); PrintClosure(c->envp, "envp", indent + 1, f); c = c->next; } } void PrintMachineState(FILE *f) { int i; char buf[256]; static int op; struct Closure *c; fputc('\n', f); for (i = 0; i < 80; ++i) fputwc(L'─', f); ksnprintf(buf, sizeof(buf), "%d\n ip %ld | op %d %s | arg %d | end %ld\n", op++, ip, mem[ip], GetOpName(mem[ip]), mem[ip + 1], end); fputs(buf, f); fputs(" term ", f); Print(ip, 0, GetDepth(envp), f); fputc('\n', f); fputc('\n', f); PrintClosure(contp, "contp", 1, f); fputc('\n', f); PrintClosure(envp, "envp", 1, f); fputc('\n', f); PrintClosure(frep, "frep", 1, f); } void PrintExpressions(FILE *f, char alog, char vlog) { int i, d; char buf[48]; struct Closure *p, ps; ps.term = ip; ps.next = contp; ps.envp = envp; for (p = &ps; p; p = p->next) { Print(p->term, 1, GetDepth(p->envp), f); if (p->next) fputc(' ', f); } if (alog) { fputs(" ⟹ ", f); switch (mem[ip]) { case VAR: ksnprintf(buf, sizeof(buf), "var[%d]", mem[ip + 1]); fputs(buf, f); break; case APP: fputs("app[", f); Print(ip + 2 + mem[ip + 1], 1, GetDepth(envp), f); fputc(']', f); break; case ABS: if (contp) { fputs("abs[", f); Print(ip + 1, 1, GetDepth(envp), f); fputc(']', f); } else { ksnprintf(buf, sizeof(buf), "bye[%d]", mem[ip + 2]); fputs(buf, f); } break; case IOP: if (ip < 22) { if (!binary) { ksnprintf(buf, sizeof(buf), "put[%c]", '0' + (int)(ip & 1)); } else if (mem[ip + 1] & 1) { ksnprintf(buf, sizeof(buf), "put[0%hho '%c']", co, isprint(co) ? co : '.'); } else { ksnprintf(buf, sizeof(buf), "wr%d[0%hho]", (int)(ip & 1), co); } fputs(buf, f); } else { fputs("gro", f); } break; default: break; } } if (vlog) { d = GetDepth(envp); for (i = 0, p = envp; p->term != -1; ++i, p = p->next) { fputc('\n', f); fputc('\t', f); PrintVar(style != 1 ? i : d - 1 - i, f); fputc('=', f); Print(p->term, 0, GetDepth(p), f); } } fputc('\n', f); }
5,078
156
jart/cosmopolitan
false
cosmopolitan/tool/lambda/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/intrin/kprintf.h" #include "libc/runtime/runtime.h" #include "tool/lambda/lib/blc.h" void Error(int rc, const char* s, ...) { va_list va; fflush(stdout); fputs("\n\33[1;31mERROR\33[37m:\t", stderr); fflush(stderr); va_start(va, s); kvprintf(s, va); va_end(va); fputs("\33[0m\n", stderr); kprintf(" ip:\t%ld\n", ip); kprintf(" end:\t%ld\n", end); kprintf(" term:\t"); PrintExpressions(stderr, 0, 1); /* Dump(0, end, stderr); */ exit(rc); }
2,322
39
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/parserom.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/lambda/lib/blc.h" static struct Parse ParseImpl(int tail, int need, FILE *f) { struct Parse p, q; int b, i, j, t, start; for (start = end;;) { if (end + 2 > TERMS) Error(5, "OUT OF TERMS"); if ((b = GetBit(f)) == -1) { if (need) Error(9, "UNFINISHED EXPRESSION"); break; } else if (b) { for (t = 0; NeedBit(f);) ++t; mem[end++] = VAR; mem[end++] = t; break; } else if (NeedBit(f)) { t = end; end += 2; p = ParseImpl(0, 1, f); q = ParseImpl(t + 2, 1, f); mem[t + 0] = APP; mem[t + 1] = q.i - (t + 2); break; } else { mem[end++] = ABS; } } p.i = start; p.n = end - start; if (p.n && tail) { /* find backwards overlaps within 8-bit displacement */ i = tail - 32768; j = start - p.n; for (i = i < 0 ? 0 : i; i <= j; ++i) { if (!memcmp(mem + i, mem + p.i, p.n * sizeof(*mem))) { memset(mem + start, -1, p.n * sizeof(*mem)); end = start; p.i = i; break; } } } return p; } /** * Parses binary lambda calculus closed expression from stream. * * If `tail` is non-zero then this subroutine will perform expensive * deduplication so that optimal ROMs may be computed ahead of time. */ struct Parse Parse(int tail, FILE *f) { return ParseImpl(tail, 0, f); }
3,222
74
jart/cosmopolitan
false
cosmopolitan/tool/lambda/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 "tool/lambda/lib/blc.h" char binary; // 8-bit char safer; // safer char style; // notation char asciiname; // <3 ascii char noname; // rewriting char rlog; // redex log char slog; // state log char alog; // action log char vlog; // variable log int co; // output character int heap; // heap usage counter long ip; // instruction pointer long end; // end of code pointer FILE *logh; // log file stdio stream struct Closure *frep; // freed closures list struct Closure *contp; // continuations stack int mem[TERMS]; // bss memory for terms struct Closure root = {.refs = 100000, .term = -1, .next = 0}; struct Closure *envp = &root;
2,666
41
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/parse.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/lambda/lib/blc.h" /** * Parses binary lambda calculus closed expression from stream. */ struct Parse Parse(int ignored, FILE* f) { int t, start; char bit, need; struct Parse p; for (need = 0, start = end;;) { if (end + 2 > TERMS) Error(5, "OUT OF TERMS"); if ((bit = GetBit(f)) == -1) { if (!need) break; fflush(stdout); fputs("---\n", stderr); Print(start, 0, 0, stderr); Error(9, "UNFINISHED EXPRESSION"); } else if (bit) { for (t = 0; NeedBit(f);) ++t; mem[end++] = VAR; mem[end++] = t; break; } else if (NeedBit(f)) { t = end; end += 2; mem[t] = APP; p = Parse(0, f); mem[t + 1] = p.n; need = 1; } else { mem[end++] = ABS; } } p.i = start; p.n = end - start; return p; }
2,665
56
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/calloc.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 "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" void *Calloc(size_t a, size_t b) { char *r; size_t z; static char *p; static size_t i; static size_t n; z = a * b; if (!p) { n = FRAMESIZE; p = mmap((void *)0x300000000000, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0); } if (i + z > n) { mmap(p + i, FRAMESIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0); n += FRAMESIZE; } r = p + i; i += z; return r; }
2,425
44
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/dump.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/kprintf.h" #include "tool/lambda/lib/blc.h" void Dumper(int i, int j, FILE *f) { char buf[64]; if (i) fputc('\n', f); for (; i < j; ++i) { switch (mem[i]) { case VAR: ksnprintf(buf, sizeof(buf), " %s,%d,\t// %2d: ", "VAR", mem[i + 1], i); fputs(buf, f); Print(i, 1, 0, f); fputc('\n', f); ++i; break; case APP: ksnprintf(buf, sizeof(buf), " %s,%d,\t// %2d: ", "APP", mem[i + 1], i); fputs(buf, f); Print(i, 1, 0, f); fputc('\n', f); ++i; break; case ABS: ksnprintf(buf, sizeof(buf), " %s,\t// %2d: ", "ABS", i); fputs(buf, f); Print(i, 1, 0, f); fputc('\n', f); break; default: ksnprintf(buf, sizeof(buf), " %d,\t// %2d: ", mem[i], i); fputs(buf, f); Print(i, 1, 0, f); fputc('\n', f); break; } } } void Dump(int i, int j, FILE *f) { fputs("\nstatic int kTerm[] = {\n", f); Dumper(i, j, f); fputs("};\n", f); }
2,941
64
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/needbit.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/lambda/lib/blc.h" char NeedBit(FILE* f) { char b = GetBit(f); if (b == -1) Error(9, "UNEXPECTED EOF"); return b; }
1,973
26
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/blc.h
#ifndef COSMOPOLITAN_TOOL_LAMBDA_LIB_BLC_H_ #define COSMOPOLITAN_TOOL_LAMBDA_LIB_BLC_H_ #include "libc/stdio/stdio.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define BUILTINS 4 #define LOC 12 #define TERMS 5000000 #define IOP 0 // code for gro, wr0, wr1, put #define VAR 1 // code for variable lookup #define APP 2 // code for applications #define ABS 3 // code for abstractions struct Parse { int n; int i; }; struct Closure { struct Closure *next; struct Closure *envp; int refs; int term; }; extern char vlog; extern char slog; extern char alog; extern char rlog; extern char safer; extern char style; extern char binary; extern char noname; extern char asciiname; extern int ci; extern int co; extern long ip; extern long end; extern int heap; extern FILE *logh; extern int mem[TERMS]; extern struct Closure root; extern struct Closure *envp; extern struct Closure *frep; extern struct Closure *contp; char GetBit(FILE *); char NeedBit(FILE *); struct Parse Parse(int, FILE *); void Dump(int, int, FILE *); void Error(int, const char *, ...); void PrintLambda(int, int, int, int, FILE *); void PrintBinary(int, int, int, FILE *); void PrintDebruijn(int, int, int, FILE *); void PrintMachineState(FILE *); void PrintExpressions(FILE *, char, char); void Print(int, int, int, FILE *); void PrintVar(int, FILE *); void *Calloc(size_t, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_LAMBDA_LIB_BLC_H_ */
1,512
66
jart/cosmopolitan
false
cosmopolitan/tool/lambda/lib/print.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 "tool/lambda/lib/blc.h" #define FREEBIES u"ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz" /* clang-format off */ #define ALPHABET \ u"abcdefghijklmnopqrsuvwxyz" \ u"αβγδεζηθιμξπρςστυφχψϑϕ" \ u"ℵℶℷℸ" \ u"идџжлђ" \ u"⅄ℏ℘þæß§£¥₿" \ u"𝘢𝘣𝘤𝘥𝘦𝘧𝘨𝘩𝘪𝘫𝘬𝘭𝘮𝘯𝘰𝘱𝘲𝘳𝘴𝘵𝘶𝘷𝘸𝘹𝘺𝘻" \ u"𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫" \ u"𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇" /* clang-format on */ static char kFalse[] = { ABS, // 0: false ABS, // 1: (λ 0) VAR, 0, // 2: 0 }; static char kTrue[] = { ABS, // 0: true ABS, // 1: (λ 1) VAR, 1, // 2: 1 }; static char kOne[] = { ABS, // 4: (λab.ab) ABS, // 5: (λa.ɐa) APP, 2, // 6: qɐ VAR, 1, // 8: q VAR, 0, // 10: ɐ }; static char kTwo[] = { ABS, // 12: (λab.a(ab)) ABS, // 13: (λa.ɐ(ɐa)) APP, 2, // 14: q(qɐ) VAR, 1, // 16: q APP, 2, // 18: qɐ VAR, 1, // 20: q VAR, 0, // 22: ɐ }; static char kThree[] = { ABS, // 24: (λab.a(a(ab))) ABS, // 25: (λa.ɐ(ɐ(ɐa))) APP, 2, // 26: q(q(qɐ)) VAR, 1, // 28: q APP, 2, // 30: q(qɐ) VAR, 1, // 32: q APP, 2, // 34: qɐ VAR, 1, // 36: q VAR, 0, // 38: ɐ }; static char kFour[] = { ABS, // 40: (λab.a(a(a(ab)))) ABS, // 41: (λa.ɐ(ɐ(ɐ(ɐa)))) APP, 2, // 42: q(q(q(qɐ))) VAR, 1, // 44: q APP, 2, // 46: q(q(qɐ)) VAR, 1, // 48: q APP, 2, // 50: q(qɐ) VAR, 1, // 52: q APP, 2, // 54: qɐ VAR, 1, // 56: q VAR, 0, // 58: ɐ }; static char kFive[] = { ABS, // 60: (λab.a(a(a(a(ab))))) ABS, // 61: (λa.ɐ(ɐ(ɐ(ɐ(ɐa))))) APP, 2, // 62: q(q(q(q(qɐ)))) VAR, 1, // 64: q APP, 2, // 66: q(q(q(qɐ))) VAR, 1, // 68: q APP, 2, // 70: q(q(qɐ)) VAR, 1, // 72: q APP, 2, // 74: q(qɐ) VAR, 1, // 76: q APP, 2, // 78: qɐ VAR, 1, // 80: q VAR, 0, // 82: ɐ }; static char kSix[] = { ABS, // 84: (λab.a(a(a(a(a(ab)))))) ABS, // 85: (λa.ɐ(ɐ(ɐ(ɐ(ɐ(ɐa)))))) APP, 2, // 86: q(q(q(q(q(qɐ))))) VAR, 1, // 88: q APP, 2, // 90: q(q(q(q(qɐ)))) VAR, 1, // 92: q APP, 2, // 94: q(q(q(qɐ))) VAR, 1, // 96: q APP, 2, // 98: q(q(qɐ)) VAR, 1, // 100: q APP, 2, // 102: q(qɐ) VAR, 1, // 104: q APP, 2, // 106: qɐ VAR, 1, // 108: q VAR, 0, // 110: ɐ }; static char kSeven[] = { ABS, // 112: (λab.a(a(a(a(a(a(ab))))))) ABS, // 113: (λa.ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐa))))))) APP, 2, // 114: q(q(q(q(q(q(qɐ)))))) VAR, 1, // 116: q APP, 2, // 118: q(q(q(q(q(qɐ))))) VAR, 1, // 120: q APP, 2, // 122: q(q(q(q(qɐ)))) VAR, 1, // 124: q APP, 2, // 126: q(q(q(qɐ))) VAR, 1, // 128: q APP, 2, // 130: q(q(qɐ)) VAR, 1, // 132: q APP, 2, // 134: q(qɐ) VAR, 1, // 136: q APP, 2, // 138: qɐ VAR, 1, // 140: q VAR, 0, // 142: ɐ }; static char kEight[] = { ABS, // 144: (λab.a(a(a(a(a(a(a(ab)))))))) ABS, // 145: (λa.ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐa)))))))) APP, 2, // 146: q(q(q(q(q(q(q(qɐ))))))) VAR, 1, // 148: q APP, 2, // 150: q(q(q(q(q(q(qɐ)))))) VAR, 1, // 152: q APP, 2, // 154: q(q(q(q(q(qɐ))))) VAR, 1, // 156: q APP, 2, // 158: q(q(q(q(qɐ)))) VAR, 1, // 160: q APP, 2, // 162: q(q(q(qɐ))) VAR, 1, // 164: q APP, 2, // 166: q(q(qɐ)) VAR, 1, // 168: q APP, 2, // 170: q(qɐ) VAR, 1, // 172: q APP, 2, // 174: qɐ VAR, 1, // 176: q VAR, 0, // 178: ɐ }; static char kNine[] = { ABS, // 180: (λab.a(a(a(a(a(a(a(a(ab))))))))) ABS, // 181: (λa.ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐ(ɐa))))))))) APP, 2, // 182: q(q(q(q(q(q(q(q(qɐ)))))))) VAR, 1, // 184: q APP, 2, // 186: q(q(q(q(q(q(q(qɐ))))))) VAR, 1, // 188: q APP, 2, // 190: q(q(q(q(q(q(qɐ)))))) VAR, 1, // 192: q APP, 2, // 194: q(q(q(q(q(qɐ))))) VAR, 1, // 196: q APP, 2, // 198: q(q(q(q(qɐ)))) VAR, 1, // 200: q APP, 2, // 202: q(q(q(qɐ))) VAR, 1, // 204: q APP, 2, // 206: q(q(qɐ)) VAR, 1, // 208: q APP, 2, // 210: q(qɐ) VAR, 1, // 212: q APP, 2, // 214: qɐ VAR, 1, // 216: q VAR, 0, // 218: ɐ }; static char kSelf[] = { ABS, // 0: λa.aa APP, 2, // 1: ɐɐ VAR, 0, // 3: ɐ VAR, 0, // 5: ɐ }; static char kOmega[] = { APP, 7, // 0: ω ω ABS, // 2: ω APP, 2, // 3: ɐ ɐ VAR, 0, // 5: ɐ VAR, 0, // 7: ɐ ABS, // 9: ω APP, 2, // 10: ɐ ɐ VAR, 0, // 12: ɐ VAR, 0, // 14: ɐ }; static char kIf[] = { ABS, // 0: if ABS, // 1: (λλ 2 1 0) ABS, // 2: (λ 2 1 0) APP, 6, // 3: 2 1 0 APP, 2, // 5: 2 1 VAR, 2, // 7: 2 VAR, 1, // 9: 1 VAR, 0, // 11: 0 }; static char kOr[] = { ABS, // 32: λab.bba ABS, // 33: λa.aaɐ APP, 6, // 34: ɐɐq APP, 2, // 36: ɐɐ VAR, 0, // 38: ɐ VAR, 0, // 40: ɐ VAR, 1, // 42: q }; static char kAnd[] = { ABS, // 32: λab.bab ABS, // 33: λa.aɐa APP, 6, // 34: ɐqɐ APP, 2, // 36: ɐq VAR, 0, // 38: ɐ VAR, 1, // 40: q VAR, 0, // 42: ɐ }; static char kNot[] = { ABS, // 32: λabc.acb ABS, // 33: λab.ɐba ABS, // 34: λa.qaɐ APP, 6, // 35: ɔɐq APP, 2, // 37: ɔɐ VAR, 2, // 39: ɔ VAR, 0, // 41: ɐ VAR, 1, // 43: q }; static char kPair[] = { ABS, // 0: (λλλ 0 2 1) ABS, // 1: (λλ 0 2 1) ABS, // 2: (λ 0 2 1) APP, 6, // 3: 0 2 1 APP, 2, // 5: 0 2 VAR, 0, // 7: 0 VAR, 2, // 9: 2 VAR, 1, // 11: 1 }; static char kFirst[] = { ABS, // 0: (λ 0 false) APP, 2, // 1: 0 false VAR, 0, // 3: 0 ABS, // 5: false ABS, // 6: (λ 0) VAR, 0, // 7: 0 }; static char kSecond[] = { ABS, // 0: (λ 0 true) APP, 2, // 1: 0 true VAR, 0, // 3: 0 ABS, // 5: true ABS, // 6: (λ 1) VAR, 1, // 7: 1 }; static char kSucc[] = { ABS, // 0: (λλλ 1 (2 1 0)) ABS, // 1: (λλ 1 (2 1 0)) ABS, // 2: (λ 1 (2 1 0)) APP, 2, // 3: 1 (2 1 0) VAR, 1, // 5: 1 APP, 6, // 7: 2 1 0 APP, 2, // 9: 2 1 VAR, 2, // 11: 2 VAR, 1, // 13: 1 VAR, 0, // 15: 0 }; static char kCompose[] = { ABS, // 0: (λλλ 2 (1 0)) ABS, // 1: (λλ 2 (1 0)) ABS, // 2: (λ 2 (1 0)) APP, 2, // 3: 2 (1 0) VAR, 2, // 5: 2 APP, 2, // 7: 1 0 VAR, 1, // 9: 1 VAR, 0, // 11: 0 }; static char kMap[] = { ABS, // 0: (λλλλ 2 (compose 1 3) 0) ABS, // 1: (λλλ 2 (compose 1 3) 0) ABS, // 2: (λλ 2 (compose 1 3) 0) ABS, // 3: (λ 2 (compose 1 3) 0) APP, 25, // 4: 2 (compose 1 3) 0 APP, 2, // 6: 2 (compose 1 3) VAR, 2, // 8: 2 APP, 17, // 10: compose 1 3 APP, 13, // 12: compose 1 ABS, // 14: compose ABS, // 15: (λλ 2 (1 0)) ABS, // 16: (λ 2 (1 0)) APP, 2, // 17: 2 (1 0) VAR, 2, // 19: 2 APP, 2, // 21: 1 0 VAR, 1, // 23: 1 VAR, 0, // 25: 0 VAR, 1, // 27: 1 VAR, 3, // 29: 3 VAR, 0, // 31: 0 }; static char kCons[] = { ABS, // 0: (λλλλ 1 3 (2 1 0)) ABS, // 1: (λλλ 1 3 (2 1 0)) ABS, // 2: (λλ 1 3 (2 1 0)) ABS, // 3: (λ 1 3 (2 1 0)) APP, 6, // 4: 1 3 (2 1 0) APP, 2, // 6: 1 3 VAR, 1, // 8: 1 VAR, 3, // 10: 3 APP, 6, // 12: 2 1 0 APP, 2, // 14: 2 1 VAR, 2, // 16: 2 VAR, 1, // 18: 1 VAR, 0, // 20: 0 }; static char kY[] = { ABS, // 32: λa.(λb.bb)(λb.a(bb)) APP, 7, // 33: (λa.aa)(λa.ɐ(aa)) ABS, // 35: λa.aa APP, 2, // 36: ɐɐ VAR, 0, // 38: ɐ VAR, 0, // 40: ɐ ABS, // 42: λa.ɐ(aa) APP, 2, // 43: q(ɐɐ) VAR, 1, // 45: q APP, 2, // 47: ɐɐ VAR, 0, // 49: ɐ VAR, 0, // 51: ɐ }; static char kYCurry[] = { ABS, // 0: (λ (λ 1 (0 0)) (λ 1 (0 0))) APP, 11, // 1: (λ 1 (0 0)) (λ 1 (0 0)) ABS, // 3: (λ 1 (0 0)) APP, 2, // 4: 1 (0 0) VAR, 1, // 6: 1 APP, 2, // 8: 0 0 VAR, 0, // 10: 0 VAR, 0, // 12: 0 ABS, // 14: (λ 1 (0 0)) APP, 2, // 15: 1 (0 0) VAR, 1, // 17: 1 APP, 2, // 19: 0 0 VAR, 0, // 21: 0 VAR, 0, // 23: 0 }; static char kIszero[] = { ABS, // 32: λabc.a(λd.c)b ABS, // 33: λab.ɐ(λc.b)a ABS, // 34: λa.q(λb.a)ɐ APP, 7, // 35: ɔ(λa.ɐ)q APP, 2, // 37: ɔ(λa.ɐ) VAR, 2, // 39: ɔ ABS, // 41: λa.ɐ VAR, 1, // 42: q VAR, 1, // 44: q }; static char kPred[] = { ABS, // 0: λabc.a(λde.e(db))(λd.c)(λd.d) ABS, // 1: λab.ɐ(λcd.d(ca))(λc.b)(λc.c) ABS, // 2: λa.q(λbc.c(bɐ))(λb.a)(λb.b) APP, 21, // 3: ɔ(λab.b(aq))(λa.ɐ)(λa.a) APP, 16, // 5: ɔ(λab.b(aq))(λa.ɐ) APP, 2, // 7: ɔ(λab.b(aq)) VAR, 2, // 9: ɔ ABS, // 11: λab.b(aq) ABS, // 12: λa.a(ɐɔ) APP, 2, // 13: ɐ(qp) VAR, 0, // 15: ɐ APP, 2, // 17: qp VAR, 1, // 19: q VAR, 3, // 21: p ABS, // 23: λa.ɐ VAR, 1, // 24: q ABS, // 26: λa.a VAR, 0, // 27: ɐ }; static char kXor[] = { ABS, // 32: λab.a(λcd.bdc)b ABS, // 33: λa.ɐ(λbc.acb)a APP, 16, // 34: q(λab.ɐba)ɐ APP, 2, // 36: q(λab.ɐba) VAR, 1, // 38: q ABS, // 40: λab.ɐba ABS, // 41: λa.qaɐ APP, 6, // 42: ɔɐq APP, 2, // 44: ɔɐ VAR, 2, // 46: ɔ VAR, 0, // 48: ɐ VAR, 1, // 50: q VAR, 0, // 52: ɐ }; static char kAdd[] = { ABS, // 29: λabcd.ac(bcd) ABS, // 30: λabc.ɐb(abc) ABS, // 31: λab.qa(ɐab) ABS, // 32: λa.ɔɐ(qɐa) APP, 6, // 33: pq(ɔqɐ) APP, 2, // 35: pq VAR, 3, // 37: p VAR, 1, // 39: q APP, 6, // 41: ɔqɐ APP, 2, // 43: ɔq VAR, 2, // 45: ɔ VAR, 1, // 47: q VAR, 0, // 49: ɐ }; static char kSub[] = { ABS, // 51: λab.b(λcde.c(λfg.g(fd))(λf.e)(λf.f))a ABS, // 52: λa.a(λbcd.b(λef.f(ec))(λe.d)(λe.e))ɐ APP, 33, // 53: ɐ(λabc.a(λde.e(db))(λd.c)(λd.d))q APP, 2, // 55: ɐ(λabc.a(λde.e(db))(λd.c)(λd.d)) VAR, 0, // 57: ɐ ABS, // 59: λabc.a(λde.e(db))(λd.c)(λd.d) ABS, // 60: λab.ɐ(λcd.d(ca))(λc.b)(λc.c) ABS, // 61: λa.q(λbc.c(bɐ))(λb.a)(λb.b) APP, 21, // 62: ɔ(λab.b(aq))(λa.ɐ)(λa.a) APP, 16, // 64: ɔ(λab.b(aq))(λa.ɐ) APP, 2, // 66: ɔ(λab.b(aq)) VAR, 2, // 68: ɔ ABS, // 70: λab.b(aq) ABS, // 71: λa.a(ɐɔ) APP, 2, // 72: ɐ(qp) VAR, 0, // 74: ɐ APP, 2, // 76: qp VAR, 1, // 78: q VAR, 3, // 80: p ABS, // 82: λa.ɐ VAR, 1, // 83: q ABS, // 85: λa.a VAR, 0, // 86: ɐ VAR, 1, // 88: q }; static char kLe[] = { ABS, // 0: λab.iszero(- a b) ABS, // 1: λa.iszero(- ɐ a) APP, 16, // 2: iszero(- q ɐ) ABS, // 4: iszero APP, 9, // 5: ɐ (λabc.c) ⊤ APP, 2, // 7: ɐ (λabc.c) VAR, 0, // 9: ɐ ABS, // 11: λabc.c ABS, // 12: ⊥ ABS, // 13: λa.a VAR, 0, // 14: ɐ ABS, // 16: ⊤ ABS, // 17: λa.ɐ VAR, 1, // 18: q APP, 43, // 20: - q ɐ APP, 39, // 22: - q ABS, // 24: - ABS, // 25: λa.a dec ɐ APP, 33, // 26: ɐ dec q APP, 2, // 28: ɐ dec VAR, 0, // 30: ɐ ABS, // 32: dec ABS, // 33: λab.ɐ (λcd.d(c a)) (λc.b) (λc.c) ABS, // 34: λa.q (λbc.c(b ɐ)) (λb.a) (λb.b) APP, 21, // 35: ɔ (λab.b(a q)) (λa.ɐ) (λa.a) APP, 16, // 37: ɔ (λab.b(a q)) (λa.ɐ) APP, 2, // 39: ɔ (λab.b(a q)) VAR, 2, // 41: ɔ ABS, // 43: λab.b(a q) ABS, // 44: λa.a(ɐ ɔ) APP, 2, // 45: ɐ(q p) VAR, 0, // 47: ɐ APP, 2, // 49: q p VAR, 1, // 51: q VAR, 3, // 53: p ABS, // 55: λa.ɐ VAR, 1, // 56: q ABS, // 58: λa.a VAR, 0, // 59: ɐ VAR, 1, // 61: q VAR, 1, // 63: q VAR, 0, // 65: ɐ }; static char kEq[] = { ABS, // 0: λab.∧(≤ a b)(≤ b a) ABS, // 1: λa.∧(≤ ɐ a)(≤ a ɐ) APP, 89, // 2: ∧(≤ q ɐ)(≤ ɐ q) APP, 12, // 4: ∧(≤ q ɐ) ABS, // 6: ∧ ABS, // 7: λa.ɐ a ɐ APP, 6, // 8: q ɐ q APP, 2, // 10: q ɐ VAR, 1, // 12: q VAR, 0, // 14: ɐ VAR, 1, // 16: q APP, 71, // 18: ≤ q ɐ APP, 67, // 20: ≤ q ABS, // 22: ≤ ABS, // 23: λa.iszero(- ɐ a) APP, 16, // 24: iszero(- q ɐ) ABS, // 26: iszero APP, 9, // 27: ɐ (λabc.c) ⊤ APP, 2, // 29: ɐ (λabc.c) VAR, 0, // 31: ɐ ABS, // 33: λabc.c ABS, // 34: ⊥ ABS, // 35: λa.a VAR, 0, // 36: ɐ ABS, // 38: ⊤ ABS, // 39: λa.ɐ VAR, 1, // 40: q APP, 43, // 42: - q ɐ APP, 39, // 44: - q ABS, // 46: - ABS, // 47: λa.a dec ɐ APP, 33, // 48: ɐ dec q APP, 2, // 50: ɐ dec VAR, 0, // 52: ɐ ABS, // 54: dec ABS, // 55: λab.ɐ (λcd.d(c a)) (λc.b) (λc.c) ABS, // 56: λa.q (λbc.c(b ɐ)) (λb.a) (λb.b) APP, 21, // 57: ɔ (λab.b(a q)) (λa.ɐ) (λa.a) APP, 16, // 59: ɔ (λab.b(a q)) (λa.ɐ) APP, 2, // 61: ɔ (λab.b(a q)) VAR, 2, // 63: ɔ ABS, // 65: λab.b(a q) ABS, // 66: λa.a(ɐ ɔ) APP, 2, // 67: ɐ(q p) VAR, 0, // 69: ɐ APP, 2, // 71: q p VAR, 1, // 73: q VAR, 3, // 75: p ABS, // 77: λa.ɐ VAR, 1, // 78: q ABS, // 80: λa.a VAR, 0, // 81: ɐ VAR, 1, // 83: q VAR, 1, // 85: q VAR, 0, // 87: ɐ VAR, 1, // 89: q VAR, 0, // 91: ɐ APP, 71, // 93: ≤ ɐ q APP, 67, // 95: ≤ ɐ ABS, // 97: ≤ ABS, // 98: λa.iszero(- ɐ a) APP, 16, // 99: iszero(- q ɐ) ABS, // 101: iszero APP, 9, // 102: ɐ (λabc.c) ⊤ APP, 2, // 104: ɐ (λabc.c) VAR, 0, // 106: ɐ ABS, // 108: λabc.c ABS, // 109: ⊥ ABS, // 110: λa.a VAR, 0, // 111: ɐ ABS, // 113: ⊤ ABS, // 114: λa.ɐ VAR, 1, // 115: q APP, 43, // 117: - q ɐ APP, 39, // 119: - q ABS, // 121: - ABS, // 122: λa.a dec ɐ APP, 33, // 123: ɐ dec q APP, 2, // 125: ɐ dec VAR, 0, // 127: ɐ ABS, // 129: dec ABS, // 130: λab.ɐ (λcd.d(c a)) (λc.b) (λc.c) ABS, // 131: λa.q (λbc.c(b ɐ)) (λb.a) (λb.b) APP, 21, // 132: ɔ (λab.b(a q)) (λa.ɐ) (λa.a) APP, 16, // 134: ɔ (λab.b(a q)) (λa.ɐ) APP, 2, // 136: ɔ (λab.b(a q)) VAR, 2, // 138: ɔ ABS, // 140: λab.b(a q) ABS, // 141: λa.a(ɐ ɔ) APP, 2, // 142: ɐ(q p) VAR, 0, // 144: ɐ APP, 2, // 146: q p VAR, 1, // 148: q VAR, 3, // 150: p ABS, // 152: λa.ɐ VAR, 1, // 153: q ABS, // 155: λa.a VAR, 0, // 156: ɐ VAR, 1, // 158: q VAR, 1, // 160: q VAR, 0, // 162: ɐ VAR, 0, // 164: ɐ VAR, 1, // 166: q }; static int termcmp(const int* p, const char* q, size_t n) { int c; size_t i; for (i = 0; i < n; ++i) { if ((c = p[i] - q[i])) { return c; } } return 0; } void PrintVar(int i, FILE* f) { char ibuf[22]; switch (style) { case 0: FormatInt64(ibuf, i); fputs(ibuf, f); break; case 1: if (0 <= i && i < sizeof(ALPHABET) / sizeof(*ALPHABET) - 1) { fputwc(ALPHABET[i], f); } else if (i < 0 && ~i < sizeof(FREEBIES) / sizeof(*FREEBIES) - 1) { fputwc(FREEBIES[~i], f); } else { ibuf[0] = '?'; FormatInt64(ibuf + 1, i); fputs(ibuf, f); } break; default: do { fputc('1', f); } while (i-- > 0); fputc('0', f); break; } } void PrintDebruijn(int x, int head, int depth, FILE* f) { char ibuf[22]; if (0 <= x && x < TERMS) { if (mem[x] == ABS) { if (!noname) { if (x == 14) { fputs("put", f); return; } if (x + sizeof(kTrue) / sizeof(*kTrue) <= end && !termcmp(mem + x, kTrue, sizeof(kTrue))) { if (asciiname) { fputs("true", f); } else { fputs("⊤", f); } return; } if (x + sizeof(kFalse) / sizeof(*kFalse) <= end && !termcmp(mem + x, kFalse, sizeof(kFalse))) { if (asciiname) { fputs("false", f); } else { fputs("⊥", f); } return; } if (x + sizeof(kOmega) / sizeof(*kOmega) <= end && !termcmp(mem + x, kOmega, sizeof(kOmega))) { if (asciiname) { fputs("omega", f); } else { fputs("Ω", f); } return; } if (x + sizeof(kSelf) / sizeof(*kSelf) <= end && !termcmp(mem + x, kSelf, sizeof(kSelf))) { if (asciiname) { fputs("omega", f); } else { fputs("ω", f); } return; } if (x + sizeof(kY) / sizeof(*kY) <= end && !termcmp(mem + x, kY, sizeof(kY))) { fputs("Y", f); return; } if (x + sizeof(kYCurry) / sizeof(*kYCurry) <= end && !termcmp(mem + x, kYCurry, sizeof(kYCurry))) { fputs("Y", f); return; } if (x + sizeof(kIf) / sizeof(*kIf) <= end && !termcmp(mem + x, kIf, sizeof(kIf))) { fputs("if", f); return; } if (x + sizeof(kPair) / sizeof(*kPair) <= end && !termcmp(mem + x, kPair, sizeof(kPair))) { fputs("pair", f); return; } if (x + sizeof(kNot) / sizeof(*kNot) <= end && !termcmp(mem + x, kNot, sizeof(kNot))) { if (asciiname) { fputs("not", f); } else { fputwc(L'¬', f); } return; } if (x + sizeof(kOr) / sizeof(*kOr) <= end && !termcmp(mem + x, kOr, sizeof(kOr))) { if (asciiname) { fputs("or", f); } else { fputwc(L'∨', f); } return; } if (x + sizeof(kAnd) / sizeof(*kAnd) <= end && !termcmp(mem + x, kAnd, sizeof(kAnd))) { if (asciiname) { fputs("and", f); } else { fputwc(L'∧', f); } return; } if (x + sizeof(kXor) / sizeof(*kXor) <= end && !termcmp(mem + x, kXor, sizeof(kXor))) { if (asciiname) { fputs("xor", f); } else { fputwc(L'⊻', f); } return; } if (x + sizeof(kLe) / sizeof(*kLe) <= end && !termcmp(mem + x, kLe, sizeof(kLe))) { if (asciiname) { fputs("le", f); } else { fputwc(L'≤', f); } return; } if (x + sizeof(kEq) / sizeof(*kEq) <= end && !termcmp(mem + x, kEq, sizeof(kEq))) { fputwc(L'=', f); return; } if (x + sizeof(kAdd) / sizeof(*kAdd) <= end && !termcmp(mem + x, kAdd, sizeof(kAdd))) { fputs("+", f); return; } if (x + sizeof(kSub) / sizeof(*kSub) <= end && !termcmp(mem + x, kSub, sizeof(kSub))) { fputs("-", f); return; } if (x + sizeof(kCompose) / sizeof(*kCompose) <= end && !termcmp(mem + x, kCompose, sizeof(kCompose))) { fputs("∘", f); return; } if (x + sizeof(kSucc) / sizeof(*kSucc) <= end && !termcmp(mem + x, kSucc, sizeof(kSucc))) { fputs("inc", f); return; } if (x + sizeof(kPred) / sizeof(*kPred) <= end && !termcmp(mem + x, kPred, sizeof(kPred))) { fputs("dec", f); return; } if (x + sizeof(kSecond) / sizeof(*kSecond) <= end && !termcmp(mem + x, kSecond, sizeof(kSecond))) { fputs("second", f); return; } if (x + sizeof(kFirst) / sizeof(*kFirst) <= end && !termcmp(mem + x, kFirst, sizeof(kFirst))) { fputs("first", f); return; } if (x + sizeof(kMap) / sizeof(*kMap) <= end && !termcmp(mem + x, kMap, sizeof(kMap))) { fputs("map", f); return; } if (x + sizeof(kIszero) / sizeof(*kIszero) <= end && !termcmp(mem + x, kIszero, sizeof(kIszero))) { fputs("iszero", f); return; } if (x + sizeof(kCons) / sizeof(*kCons) <= end && !termcmp(mem + x, kCons, sizeof(kCons))) { fputs("cons", f); return; } if (x + sizeof(kOne) / sizeof(*kOne) <= end && !termcmp(mem + x, kOne, sizeof(kOne))) { fputs("one", f); return; } if (x + sizeof(kTwo) / sizeof(*kTwo) <= end && !termcmp(mem + x, kTwo, sizeof(kTwo))) { fputs("two", f); return; } if (x + sizeof(kThree) / sizeof(*kThree) <= end && !termcmp(mem + x, kThree, sizeof(kThree))) { fputs("three", f); return; } if (x + sizeof(kFour) / sizeof(*kFour) <= end && !termcmp(mem + x, kFour, sizeof(kFour))) { fputs("four", f); return; } if (x + sizeof(kFive) / sizeof(*kFive) <= end && !termcmp(mem + x, kFive, sizeof(kFive))) { fputs("five", f); return; } if (x + sizeof(kSix) / sizeof(*kSix) <= end && !termcmp(mem + x, kSix, sizeof(kSix))) { fputs("six", f); return; } if (x + sizeof(kSeven) / sizeof(*kSeven) <= end && !termcmp(mem + x, kSeven, sizeof(kSeven))) { fputs("seven", f); return; } if (x + sizeof(kEight) / sizeof(*kEight) <= end && !termcmp(mem + x, kEight, sizeof(kEight))) { fputs("eight", f); return; } if (x + sizeof(kNine) / sizeof(*kNine) <= end && !termcmp(mem + x, kNine, sizeof(kNine))) { fputs("nine", f); return; } } do { ++x; if (asciiname) { fputc('\\', f); } else { fputwc(L'λ', f); } if (!(0 <= x && x < TERMS)) goto Overflow; } while (mem[x] == ABS); fputc(' ', f); } if (!(0 <= (x + 1) && (x + 1) < TERMS)) goto Overflow; if (mem[x] == APP) { fputc('[', f); PrintDebruijn(x + 2, 1, depth, f); fputc(' ', f); PrintDebruijn(x + 2 + mem[x + 1], 0, depth, f); fputc(']', f); } else if (mem[x] == VAR) { if (0 <= x + 1 && x + 1 < TERMS) { PrintVar(mem[x + 1], f); } else { fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } } else if (mem[x] == IOP) { if (x < 22) { if (mem[x + 1] & 1) { fputs("put", f); } else if (x & 1) { fputs("wr1", f); } else { fputs("wr0", f); } } else if (x == end) { fputs(asciiname ? "gro" : "⋯", f); } else { fputc(L'!', f); FormatInt64(ibuf, x); fputs(ibuf, f); } } else { fputc(L'!', f); FormatInt64(ibuf, x); fputs(ibuf, f); } return; } Overflow: fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } void PrintLambda(int x, int head, int depth, int apps, FILE* f) { int close = 0; char ibuf[22]; if (0 <= x && x < TERMS) { if (mem[x] == ABS) { if (!noname) { if (x == 14) { if (asciiname) { fputs("put", f); } else { fputs("⍆", f); } return; } if (x + sizeof(kTrue) / sizeof(*kTrue) <= end && !termcmp(mem + x, kTrue, sizeof(kTrue))) { if (asciiname) { fputs("true", f); } else { fputs("⊤", f); } return; } if (x + sizeof(kFalse) / sizeof(*kFalse) <= end && !termcmp(mem + x, kFalse, sizeof(kFalse))) { if (asciiname) { fputs("false", f); } else { fputs("⊥", f); } return; } if (x + sizeof(kY) / sizeof(*kY) <= end && !termcmp(mem + x, kY, sizeof(kY))) { fputs("Y", f); return; } if (x + sizeof(kYCurry) / sizeof(*kYCurry) <= end && !termcmp(mem + x, kYCurry, sizeof(kYCurry))) { fputs("Y", f); return; } if (x + sizeof(kOmega) / sizeof(*kOmega) <= end && !termcmp(mem + x, kOmega, sizeof(kOmega))) { if (asciiname) { fputs("OMEGA", f); } else { fputs("Ω", f); } return; } if (x + sizeof(kSelf) / sizeof(*kSelf) <= end && !termcmp(mem + x, kSelf, sizeof(kSelf))) { if (asciiname) { fputs("omega", f); } else { fputs("ω", f); } return; } if (x + sizeof(kNot) / sizeof(*kNot) <= end && !termcmp(mem + x, kNot, sizeof(kNot))) { if (asciiname) { fputs("not", f); } else { fputwc(L'¬', f); } return; } if (x + sizeof(kOr) / sizeof(*kOr) <= end && !termcmp(mem + x, kOr, sizeof(kOr))) { if (asciiname) { fputs("or", f); } else { fputwc(L'∨', f); } return; } if (x + sizeof(kXor) / sizeof(*kXor) <= end && !termcmp(mem + x, kXor, sizeof(kXor))) { if (asciiname) { fputs("xor", f); } else { fputwc(L'⊻', f); } return; } if (x + sizeof(kLe) / sizeof(*kLe) <= end && !termcmp(mem + x, kLe, sizeof(kLe))) { if (asciiname) { fputs("le", f); } else { fputwc(L'≤', f); } return; } if (x + sizeof(kEq) / sizeof(*kEq) <= end && !termcmp(mem + x, kEq, sizeof(kEq))) { fputwc(L'=', f); return; } if (x + sizeof(kAnd) / sizeof(*kAnd) <= end && !termcmp(mem + x, kAnd, sizeof(kAnd))) { if (asciiname) { fputs("and", f); } else { fputwc(L'∧', f); } return; } if (x + sizeof(kAdd) / sizeof(*kAdd) <= end && !termcmp(mem + x, kAdd, sizeof(kAdd))) { fputs("+", f); return; } if (x + sizeof(kSub) / sizeof(*kSub) <= end && !termcmp(mem + x, kSub, sizeof(kSub))) { fputs("-", f); return; } if (x + sizeof(kCompose) / sizeof(*kCompose) <= end && !termcmp(mem + x, kCompose, sizeof(kCompose))) { if (asciiname) { fputs("compose", f); } else { fputs("∘", f); } return; } if (x + sizeof(kOne) / sizeof(*kOne) <= end && !termcmp(mem + x, kOne, sizeof(kOne))) { fputc('1', f); return; } if (x + sizeof(kTwo) / sizeof(*kTwo) <= end && !termcmp(mem + x, kTwo, sizeof(kTwo))) { fputc('2', f); return; } if (x + sizeof(kThree) / sizeof(*kThree) <= end && !termcmp(mem + x, kThree, sizeof(kThree))) { fputc('3', f); return; } if (x + sizeof(kFour) / sizeof(*kFour) <= end && !termcmp(mem + x, kFour, sizeof(kFour))) { fputc('4', f); return; } if (x + sizeof(kFive) / sizeof(*kFive) <= end && !termcmp(mem + x, kFive, sizeof(kFive))) { fputc('5', f); return; } if (x + sizeof(kSix) / sizeof(*kSix) <= end && !termcmp(mem + x, kSix, sizeof(kSix))) { fputc('6', f); return; } if (x + sizeof(kSeven) / sizeof(*kSeven) <= end && !termcmp(mem + x, kSeven, sizeof(kSeven))) { fputc('7', f); return; } if (x + sizeof(kEight) / sizeof(*kEight) <= end && !termcmp(mem + x, kEight, sizeof(kEight))) { fputc('8', f); return; } if (x + sizeof(kNine) / sizeof(*kNine) <= end && !termcmp(mem + x, kNine, sizeof(kNine))) { fputc('9', f); return; } if (x + sizeof(kIf) / sizeof(*kIf) <= end && !termcmp(mem + x, kIf, sizeof(kIf))) { fputs("if", f); return; } if (x + sizeof(kPair) / sizeof(*kPair) <= end && !termcmp(mem + x, kPair, sizeof(kPair))) { fputs("pair", f); return; } if (x + sizeof(kSucc) / sizeof(*kSucc) <= end && !termcmp(mem + x, kSucc, sizeof(kSucc))) { fputs("inc", f); return; } if (x + sizeof(kPred) / sizeof(*kPred) <= end && !termcmp(mem + x, kPred, sizeof(kPred))) { fputs("dec", f); return; } if (x + sizeof(kSecond) / sizeof(*kSecond) <= end && !termcmp(mem + x, kSecond, sizeof(kSecond))) { fputs("second", f); return; } if (x + sizeof(kFirst) / sizeof(*kFirst) <= end && !termcmp(mem + x, kFirst, sizeof(kFirst))) { fputs("first", f); return; } if (x + sizeof(kMap) / sizeof(*kMap) <= end && !termcmp(mem + x, kMap, sizeof(kMap))) { fputs("map", f); return; } if (x + sizeof(kIszero) / sizeof(*kIszero) <= end && !termcmp(mem + x, kIszero, sizeof(kIszero))) { fputs("iszero", f); return; } if (x + sizeof(kCons) / sizeof(*kCons) <= end && !termcmp(mem + x, kCons, sizeof(kCons))) { fputs("cons", f); return; } } if (apps) { fputc('(', f); close = 1; } if (asciiname) { fputc('\\', f); } else { fputwc(L'λ', f); } if (safer) { fputwc(ALPHABET[depth++], f); fputc('.', f); PrintLambda(x + 1, head, depth, apps + 1, f); if (close) { fputc(')', f); } return; } do { ++x; fputwc(ALPHABET[depth++], f); if (!(0 <= x && x < TERMS)) goto Overflow; } while (mem[x] == ABS); fputc('.', f); } if (!(0 <= (x + 1) && (x + 1) < TERMS)) goto Overflow; if (mem[x] == VAR) { if (0 <= x + 1 && x + 1 < TERMS) { PrintVar(depth - 1 - mem[x + 1], f); } else { fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } } else if (mem[x] == APP) { if (!close && !head) { fputc('(', f); close = 1; } PrintLambda(x + 2, 1, depth, apps + 1, f); if (!(x + 2 + mem[x + 1] < TERMS && mem[x + 2 + mem[x + 1]] == APP)) { if (safer || !noname) fputc(' ', f); } PrintLambda(x + 2 + mem[x + 1], 0, depth, apps + 1, f); } else if (mem[x] == IOP) { if (x < 22) { if (mem[x + 1] & 1) { fputs(asciiname ? "put" : "⍆", f); } else if (x & 1) { fputs(asciiname ? "wr1" : "⍆₁", f); } else { fputs(asciiname ? "wr0" : "⍆₀", f); } } else if (x == end) { fputs(asciiname ? "gro" : "⋯", f); } else { fputc(L'!', f); FormatInt64(ibuf, x); fputs(ibuf, f); } } else { fputc(L'!', f); FormatInt64(ibuf, x); fputs(ibuf, f); } if (close) { fputc(')', f); } return; } Overflow: fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } void PrintBinary(int x, int head, int depth, FILE* f) { char ibuf[22]; if (0 <= x && x < TERMS) { if (mem[x] == ABS) { if (x == 14) { fputs("⍆", f); return; } do { ++x; ++depth; fputc('0', f); fputc('0', f); if (!(0 <= x && x < TERMS)) goto Overflow; } while (mem[x] == ABS); } if (!(0 <= (x + 1) && (x + 1) < TERMS)) goto Overflow; if (mem[x] == VAR) { if (0 <= x + 1 && x + 1 < TERMS) { PrintVar(mem[x + 1], f); } else { fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } } else if (mem[x] == APP) { fputc('0', f); fputc('1', f); PrintBinary(x + 2, 0, 0, f); PrintBinary(x + 2 + mem[x + 1], 0, 0, f); } else if (mem[x] == IOP) { if (x < 22) { if (mem[x + 1] & 1) { fputs("⍆", f); } else if (x & 1) { fputs("⍆₁", f); } else { fputs("⍆₀", f); } } else { fputwc(L'⋯', f); } } else if (mem[x] == -1) { fputwc(L'⋯', f); } else { fputc(L'!', f); FormatInt64(ibuf, x); fputs(ibuf, f); } return; } Overflow: fputc(L'‼', f); FormatInt64(ibuf, x); fputs(ibuf, f); } void Print(int x, int head, int depth, FILE* f) { switch (style) { case 0: PrintDebruijn(x, head, depth, f); break; case 1: PrintLambda(x, head, depth, 0, f); break; default: PrintBinary(x, head, depth, f); break; } }
36,710
1,290
jart/cosmopolitan
false
cosmopolitan/tool/viz/generatetortureimage.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/mem/gc.h" #include "libc/str/str.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "third_party/stb/stb_image_write.h" #define YN (1080 / YM) #define XN (1920 / XM) #define YM 2 #define XM 2 void *GenerateTortureImage(unsigned char RGB[YN][YM][XN][XM][3]) { long y, x, i, j, b, r, g; for (y = 0; y < YN; ++y) { for (x = 0; x < XN; ++x) { if ((y & 1) ^ (x & 1)) { r = 255; g = 255; b = 0; } else { r = 0; g = 0; b = 255; } for (i = 0; i < YM; ++i) { for (j = 0; j < XM; ++j) { RGB[y][i][x][j][0] = r; RGB[y][i][x][j][1] = g; RGB[y][i][x][j][2] = b; } } } } return RGB; } int main(int argc, char *argv[]) { stbi_write_png( _gc(xasprintf("maxwell_%dx%d_%dx%d.png", XN * XM, YN * YM, XM, YM)), XN * XM, YN * YM, 3, GenerateTortureImage( _gc(xmemalign(32, sizeof(unsigned char) * XN * XM * YN * YM * 3))), XN * XM * 3); return 0; }
2,873
64
jart/cosmopolitan
false
cosmopolitan/tool/viz/tcp.c
#if 0 /*─────────────────────────────────────────────────────────────────╗ │ To the extent possible under law, Justine Tunney has waived │ │ all copyright and related or neighboring rights to this file, │ │ as it is written in the following disclaimers: │ │ • http://unlicense.org/ │ │ • http://creativecommons.org/publicdomain/zero/1.0/ │ ╚─────────────────────────────────────────────────────────────────*/ #endif #include "libc/intrin/bits.h" #include "libc/stdio/stdio.h" // clang-format off static char ip[] = "\ \x45\x00\x00\x3c\xc8\xbc\x40\x00\x40\x06\x48\xf6\x7f\x0a\x0a\x7a\ \x7f\x0a\x0a\x7c\xe2\x24\x1b\x58\xf6\xe9\xf2\x85\x00\x00\x00\x00\ \xa0\x02\xfa\xf0\x5f\xac\x00\x00\x02\x04\x05\xb4\x04\x02\x08\x0a\ \x4a\x43\x93\x29\x00\x00\x00\x00\x01\x03\x03\x07"; static const char *const kTcpOptionNames[] = { [0] = "End of Option List", [1] = "No-Operation", [2] = "Maximum Segment Size", [3] = "Window Scale", [4] = "SACK Permitted", [5] = "SACK", [6] = "Echo (obsoleted by option 8)", [7] = "Echo Reply (obsoleted by option 8)", [8] = "Timestamps", [9] = "Partial Order Connection Permitted (obsolete)", [10] = "Partial Order Service Profile (obsolete)", [11] = "CC (obsolete)", [12] = "CC.NEW (obsolete)", [13] = "CC.ECHO (obsolete)", [14] = "TCP Alternate Checksum Request (obsolete)", [15] = "TCP Alternate Checksum Data (obsolete)", [16] = "Skeeter", [17] = "Bubba", [18] = "Trailer Checksum Option", [19] = "MD5 Signature Option (obsoleted by option 29)", [20] = "SCPS Capabilities", [21] = "Selective Negative Acknowledgements", [22] = "Record Boundaries", [23] = "Corruption experienced", [24] = "SNAP", [25] = "Unassigned (released 2000-12-18)", [26] = "TCP Compression Filter", [27] = "Quick-Start Response", [28] = "User Timeout Option", [29] = "TCP Authentication Option (TCP-AO)", [30] = "Multipath TCP (MPTCP)", [31] = "Reserved (known unauthorized use without proper IANA assignm", [32] = "Reserved (known unauthorized use without proper IANA assignm", [33] = "Reserved (known unauthorized use without proper IANA assignm", [34] = "variable TCP Fast Open Cookie", [35] = "Reserved", [69] = "Encryption Negotiation", [253] = "RFC3692-1", [254] = "RFC3692-2", }; int main(int argc, char *argv[]) { int version = (ip[0] & 0b11110000) >> 4; int ihl = (ip[0] & 0b00001111) >> 0; int dscp = (ip[1] & 0b11111100) >> 2; int ecn = (ip[1] & 0b00000011) >> 0; int lengthtotal = READ16BE(ip + 2); int identification = READ16BE(ip + 4); int flags = (ip[6] & 0b11100000) >> 5; int fragmentoffset = (ip[6] & 0b00011111) << 8 | (ip[7] & 255); int ttl = ip[8] & 255; int protocol = ip[9] & 255; int ipchecksum = (ip[10] & 255) << 8 | (ip[11] & 255); int srcip = READ32BE(ip + 12); int dstip = READ32BE(ip + 16); printf("\n"); printf("// version = %u\n", version); printf("// ihl = %u\n", ihl * 4); printf("// dscp = %u\n", dscp); printf("// ecn = %u\n", ecn); printf("// lengthtotal = %u\n", lengthtotal); printf("// identification = %u\n", identification); printf("// flags = %u\n", flags); printf("// fragmentoffset = %u\n", fragmentoffset); printf("// ttl = %u\n", ttl); printf("// protocol = %u\n", protocol); printf("// ipchecksum = %u\n", ipchecksum); printf("// srcip = %hhu.%hhu.%hhu.%hhu\n", srcip >> 24, srcip >> 16, srcip >> 8, srcip); printf("// dstip = %hhu.%hhu.%hhu.%hhu\n", dstip >> 24, dstip >> 16, dstip >> 8, dstip); printf("// \n"); char *tcp = ip + ihl * 4; int srcport = READ16BE(tcp + 0); int dstport = READ16BE(tcp + 2); int sequence = READ32BE(tcp + 4); int acknumber = READ32BE(tcp + 8); int dataoffset = (tcp[12] & 0b11110000) >> 4; bool ns = !!(tcp[12] & 0b00000001); bool cwr = !!(tcp[13] & 0b10000000); bool ece = !!(tcp[13] & 0b01000000); bool urg = !!(tcp[13] & 0b00100000); bool ack = !!(tcp[13] & 0b00010000); bool psh = !!(tcp[13] & 0b00001000); bool rst = !!(tcp[13] & 0b00000100); bool syn = !!(tcp[13] & 0b00000010); bool fin = !!(tcp[13] & 0b00000001); int wsize = READ16BE(tcp + 14); int tcpchecksum = READ16BE(tcp + 16); int urgpointer = READ16BE(tcp + 18); printf("// srcport = %u\n", srcport); printf("// dstport = %u\n", dstport); printf("// sequence = %u\n", sequence); printf("// acknumber = %u\n", acknumber); printf("// dataoffset = %u\n", dataoffset); printf("// ns = %u\n", ns); printf("// cwr = %u\n", cwr); printf("// ece = %u\n", ece); printf("// urg = %u\n", urg); printf("// ack = %u\n", ack); printf("// psh = %u\n", psh); printf("// rst = %u\n", rst); printf("// syn = %u\n", syn); printf("// fin = %u\n", fin); printf("// wsize = %u\n", wsize); printf("// tcpchecksum = %u\n", tcpchecksum); printf("// urgpointer = %u\n", urgpointer); printf("// \n"); int c, i, j, n; for (i = 20; i + 1 < dataoffset * 4;) { printf("// option"); switch ((c = tcp[i] & 255)) { case 0: case 1: printf(" %u", c); ++i; break; default: n = tcp[i + 1] & 255; printf(" %u %u", c, n); for (j = 2; j < n; ++j) { printf(" %u", tcp[i + j] & 255); } i += n; break; } if (kTcpOptionNames[c]) { printf(" (%s)", kTcpOptionNames[c]); } printf("\n"); } return 0; }
5,975
157
jart/cosmopolitan
false
cosmopolitan/tool/viz/magikarp.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 "dsp/core/c1331.h" #include "dsp/core/c161.h" #include "dsp/core/core.h" #include "dsp/scale/scale.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image.h" #include "tool/viz/lib/bilinearscale.h" #include "tool/viz/lib/graphic.h" #define LONG long #define CHAR char #define CLAMP(X) MIN(255, MAX(0, X)) #define C13(A, B) (((A) + 3 * (B) + 2) >> 2) #define LERP(X, Y, P) ((X) + (((P) * ((Y) - (X))) >> 8)) static double r_; static unsigned char ChessBoard(unsigned y, unsigned x, unsigned char a, unsigned char b) { return !((y ^ x) & (1u << 2)) ? a : b; } static unsigned char AlphaBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 255, 200); } static unsigned char OutOfBoundsBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 40, 80); } static unsigned char Opacify(CHAR w, const unsigned char P[1u << w][1u << w], const unsigned char A[1u << w][1u << w], LONG yn, LONG xn, long y, long x) { if ((0 <= y && y < yn) && (0 <= x && x < xn)) { return LERP(AlphaBackground(y, x), P[y][x], A[y][x]); } else { return OutOfBoundsBackground(y, x); } } static void PrintImage(CHAR w, unsigned char R[1u << w][1u << w], unsigned char G[1u << w][1u << w], unsigned char B[1u << w][1u << w], unsigned char A[1u << w][1u << w], LONG yn, LONG xn) { bool didhalfy; long y, x; didhalfy = false; for (y = 0; y < yn; y += 2) { if (y) printf("\e[0m\n"); for (x = 0; x < xn; ++x) { printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄", Opacify(w, R, A, yn, xn, y + 0, x), Opacify(w, G, A, yn, xn, y + 0, x), Opacify(w, B, A, yn, xn, y + 0, x), Opacify(w, R, A, yn, xn, y + 1, x), Opacify(w, G, A, yn, xn, y + 1, x), Opacify(w, B, A, yn, xn, y + 1, x)); } if (y == 0) { printf("\e[0m‾0"); } else if (yn / 2 <= y && y <= yn / 2 + 1 && !didhalfy) { printf("\e[0m‾%s%s", "yn/2", y % 2 ? "+1" : ""); didhalfy = true; } else if (y + 1 == yn / 2 && !didhalfy) { printf("\e[0m⎯yn/2"); didhalfy = true; } else if (y + 1 == yn) { printf("\e[0m⎯yn"); } else if (y + 2 == yn) { printf("\e[0m_yn"); } else if (!(y % 10)) { printf("\e[0m‾%,u", y); } } printf("\e[0m\n"); } static void DeblinterlaceRgba(CHAR w, unsigned char R[1u << w][1u << w], unsigned char G[1u << w][1u << w], unsigned char B[1u << w][1u << w], unsigned char A[1u << w][1u << w], LONG yn, LONG xn, const unsigned char src[yn][xn][4]) { long y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { R[y][x] = src[y][x][0]; G[y][x] = src[y][x][1]; B[y][x] = src[y][x][2]; A[y][x] = src[y][x][3]; } } } static void SharpenX(CHAR w, unsigned char dst[1u << w][1u << w], const unsigned char src[1u << w][1u << w], char yw, char xw) { int y, x; for (y = 0; y < (1u << yw); ++y) { for (x = 0; x < (1u << xw); ++x) { dst[y][x] = C161(src[y][MAX(0, x - 1)], src[y][x], src[y][MIN((1u << xw) - 1, x + 1)]); } } } static void SharpenY(CHAR w, unsigned char dst[1u << w][1u << w], const unsigned char src[1u << w][1u << w], char yw, char xw) { int y, x; for (y = 0; y < (1u << yw); ++y) { for (x = 0; x < (1u << xw); ++x) { dst[y][x] = C161(src[MAX(0, y - 1)][x], src[y][x], src[MIN((1u << yw) - 1, y + 1)][x]); } } } static void UpscaleX(CHAR w, unsigned char img[1u << w][1u << w], char yw, char xw) { long y, x; for (y = (1u << yw); y--;) { for (x = (1u << xw); --x;) { img[y][x] = C13(img[y][MIN(((1u << xw) >> 1) - 1, (x >> 1) - 1 + (x & 1) * 2)], img[y][x >> 1]); } } } static void UpscaleY(CHAR w, unsigned char img[1u << w][1u << w], char yw, char xw) { long y, x; for (y = (1u << yw); --y;) { for (x = (1u << xw); x--;) { img[y][x] = C13(img[MIN(((1u << yw) >> 1) - 1, (y >> 1) - 1 + (y & 1) * 2)][x], img[y >> 1][x]); } } } static void Upscale(CHAR w, unsigned char img[1u << w][1u << w], unsigned char tmp[1u << w][1u << w], char yw, char xw) { UpscaleY(w, img, yw, xw - 1); SharpenY(w, tmp, img, yw, xw - 1); UpscaleX(w, tmp, yw, xw); SharpenX(w, img, tmp, yw, xw); } #if 0 static void *MagikarpY(CHAR w, unsigned char p[1u << w][1u << w], char yw, char xw) { long y, x, yn, xn, ym; unsigned char(*t)[(1u << w) + 2][1u << w]; t = memalign(64, ((1u << w) + 2) * (1u << w)); bzero(t, ((1u << w) + 2) * (1u << w)); yn = 1u << yw; xn = 1u << xw; ym = yn >> 1; for (y = 0; y < ym; ++y) { for (x = 0; x < xn; ++x) { (*t)[y + 1][x] = C1331(y ? p[(y << 1) - 1][x] : 0, p[y << 1][x], p[(y << 1) + 1][x], p[MIN(yn - 1, (y << 1) + 2)][x]); } } for (y = 0; y < ym; ++y) { for (x = 0; x < xn; ++x) { p[y][x] = C161((*t)[y + 1 - 1][x], (*t)[y + 1 + 0][x], (*t)[y + 1 + 1][x]); } } free(t); return p; } static void *MagikarpX(CHAR w, unsigned char p[1u << w][1u << w], char yw, char xw) { int y, x; LONG yn, xn, xm; yn = 1u << yw; xn = 1u << xw; xm = xn >> 1; for (x = 0; x < xm; ++x) { for (y = 0; y < yn; ++y) { p[y][(xn - xm - 1) + (xm - x - 1)] = C1331(p[y][MAX(00 + 0, xn - (x << 1) - 1 + (xn & 1) - 1)], p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 0)], p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 1)], p[y][MIN(xn - 1, xn - (x << 1) - 1 + (xn & 1) + 2)]); } } for (x = 0; x < xm; ++x) { for (y = 0; y < yn; ++y) { p[y][x] = C161(p[y][MAX(xn - 1 - xm, xn - xm - 1 + x - 1)], p[y][MIN(xn - 1 - 00, xn - xm - 1 + x + 0)], p[y][MIN(xn - 1 - 00, xn - xm - 1 + x + 1)]); } } return p; } static void ProcessImageVerbatim(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { CHAR w; void *R, *G, *B, *A; w = _roundup2log(MAX(yn, xn)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn, xn, img); PrintImage(w, R, G, B, A, yn, xn); free(R); free(G); free(B); free(A); } static void ProcessImageDouble(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { CHAR w; void *t, *R, *G, *B, *A; w = _roundup2log(MAX(yn, xn)) + 1; t = xvalloc((1u << w) * (1u << w)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn, xn, img); Upscale(w, R, t, w, w); Upscale(w, G, t, w, w); Upscale(w, B, t, w, w); Upscale(w, A, t, w, w); free(t); PrintImage(w, R, G, B, A, yn * 2, xn * 2); free(R); free(G); free(B); free(A); } static void ProcessImageHalf(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { CHAR w; void *R, *G, *B, *A; w = _roundup2log(MAX(yn, xn)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn, xn, img); MagikarpY(w, R, w, w); MagikarpY(w, G, w, w); MagikarpY(w, B, w, w); MagikarpY(w, A, w, w); MagikarpX(w, R, w - 1, w); MagikarpX(w, G, w - 1, w); MagikarpX(w, B, w - 1, w); MagikarpX(w, A, w - 1, w); PrintImage(w, R, G, B, A, yn >> 1, xn >> 1); free(R); free(G); free(B); free(A); } static void ProcessImageHalfY(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { CHAR w; void *R, *G, *B, *A; w = _roundup2log(MAX(yn, xn)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn, xn, img); MagikarpY(w, R, w, w); MagikarpY(w, G, w, w); MagikarpY(w, B, w, w); MagikarpY(w, A, w, w); PrintImage(w, R, G, B, A, yn >> 1, xn); free(R); free(G); free(B); free(A); } static void ProcessImageHalfLanczos(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { CHAR w; void *t, *R, *G, *B, *A; t = xvalloc((yn >> 1) * (xn >> 1) * 4); lanczos1b(yn >> 1, xn >> 1, t, yn, xn, &img[0][0][0]); w = _roundup2log(MAX(yn >> 1, xn >> 1)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn >> 1, xn >> 1, img); free(t); PrintImage(w, R, G, B, A, yn >> 1, xn >> 1); free(R); free(G); free(B); free(A); } static void ProcessImageWash(LONG yn, LONG xn, unsigned char img[yn][xn][4]) { long w; void *R, *G, *B, *A, *t; w = _roundup2log(MAX(yn, xn)) + 1; t = xvalloc((1u << w) * (1u << w)); R = xvalloc((1u << w) * (1u << w)); G = xvalloc((1u << w) * (1u << w)); B = xvalloc((1u << w) * (1u << w)); A = xvalloc((1u << w) * (1u << w)); DeblinterlaceRgba(w, R, G, B, A, yn, xn, img); Upscale(w, R, t, w, w); Upscale(w, G, t, w, w); Upscale(w, B, t, w, w); Upscale(w, A, t, w, w); MagikarpY(w, R, w, w); MagikarpY(w, G, w, w); MagikarpY(w, B, w, w); MagikarpY(w, A, w, w); MagikarpX(w, R, w - 1, w); MagikarpX(w, G, w - 1, w); MagikarpX(w, B, w - 1, w); MagikarpX(w, A, w - 1, w); free(t); PrintImage(w, R, G, B, A, yn, xn); free(R); free(G); free(B); free(A); } #endif #if 0 static void *MagikarpY(size_t ys, size_t xs, unsigned char p[ys][xs], size_t yn, size_t xn) { int y, x, h, b; b = yn % 2; h = yn / 2; if (b && yn < ys) yn++; for (y = b; y < h + b; ++y) { for (x = 0; x < xn; ++x) { p[(yn - h - 1) + (h - y - 1)][x] = C1331(p[MAX(00 + 0, yn - y * 2 - 1 - 1)][x], p[MIN(yn - 1, yn - y * 2 - 1 + 0)][x], p[MIN(yn - 1, yn - y * 2 - 1 + 1)][x], p[MIN(yn - 1, yn - y * 2 - 1 + 2)][x]); } } for (y = b; y < h + b; ++y) { for (x = 0; x < xn; ++x) { p[y][x] = C161(p[MAX(yn - 1 - h, yn - h - 1 + y - 1)][x], p[MIN(yn - 1 - 0, yn - h - 1 + y + 0)][x], p[MIN(yn - 1 - 0, yn - h - 1 + y + 1)][x]); } } return p; } #endif #if 0 static void *MagikarpX(size_t ys, size_t xs, unsigned char p[ys][xs], size_t yn, size_t xn) { int y, x, w, b; b = xn % 2; w = xn / 2; if (b && xn < xs) xn++; for (x = 0; x < w; ++x) { for (y = b; y < yn + b; ++y) { p[y][(xn - w - 1) + (w - x - 1)] = C1331(p[y][MAX(00 + 0, xn - x * 2 - 1 - 1)], p[y][MIN(xn - 1, xn - x * 2 - 1 + 0)], p[y][MIN(xn - 1, xn - x * 2 - 1 + 1)], p[y][MIN(xn - 1, xn - x * 2 - 1 + 2)]); } } for (x = 0; x < w; ++x) { for (y = b; y < yn + b; ++y) { p[y][x] = C161(p[y][MAX(xn - 1 - w, xn - w - 1 + x - 1)], p[y][MIN(xn - 1 - 0, xn - w - 1 + x + 0)], p[y][MIN(xn - 1 - 0, xn - w - 1 + x + 1)]); } } return p; } #endif #if 0 static void ProcessImageMagikarpImpl(CHAR sw, unsigned char src[5][1u << sw][1u << sw], LONG syn, LONG sxn, const unsigned char img[syn][sxn][4], LONG dyn, LONG dxn) { DeblinterlaceRgba2(sw, src, syn, sxn, img); MagikarpY(sw, src[0], sw, sw); MagikarpX(sw, src[0], sw - 1, sw); MagikarpY(sw, src[1], sw, sw); MagikarpX(sw, src[1], sw - 1, sw); MagikarpY(sw, src[2], sw, sw); MagikarpX(sw, src[2], sw - 1, sw); BilinearScale(sw, src[4], sw, src[3], dyn, dxn, syn, sxn); memcpy(src[3], src[4], syn * sxn); PrintImage2(sw, src, dyn, dxn); } static void ProcessImageMagikarp(LONG syn, LONG sxn, unsigned char img[syn][sxn][4]) { CHAR sw; LONG dyn, dxn; dyn = syn >> 1; dxn = sxn >> 1; sw = _roundup2log(MAX(syn, sxn)); ProcessImageMagikarpImpl(sw, gc(xvalloc((1u << sw) * (1u << sw) * 5)), syn, sxn, img, dyn, dxn); } #endif /* ******************************************************************************** */ static unsigned char Opacify2(unsigned yw, unsigned xw, const unsigned char P[yw][xw], const unsigned char A[yw][xw], unsigned yn, unsigned xn, unsigned y, unsigned x) { if ((0 <= y && y < yn) && (0 <= x && x < xn)) { return LERP(AlphaBackground(y, x), P[y][x], A[y][x]); } else { return OutOfBoundsBackground(y, x); } } static dontinline void PrintImage2(unsigned yw, unsigned xw, unsigned char img[4][yw][xw], unsigned yn, unsigned xn) { bool didhalfy; unsigned y, x; didhalfy = false; for (y = 0; y < yn; y += 2) { if (y) printf("\e[0m\n"); for (x = 0; x < xn; ++x) { printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄", Opacify2(yw, xw, img[0], img[3], yn, xn, y + 0, x), Opacify2(yw, xw, img[1], img[3], yn, xn, y + 0, x), Opacify2(yw, xw, img[2], img[3], yn, xn, y + 0, x), Opacify2(yw, xw, img[0], img[3], yn, xn, y + 1, x), Opacify2(yw, xw, img[1], img[3], yn, xn, y + 1, x), Opacify2(yw, xw, img[2], img[3], yn, xn, y + 1, x)); } if (y == 0) { printf("\e[0m‾0"); } else if (yn / 2 <= y && y <= yn / 2 + 1 && !didhalfy) { printf("\e[0m‾%s%s", "yn/2", y % 2 ? "+1" : ""); didhalfy = true; } else if (y + 1 == yn / 2 && !didhalfy) { printf("\e[0m⎯yn/2"); didhalfy = true; } else if (y + 1 == yn) { printf("\e[0m⎯yn"); } else if (y + 2 == yn) { printf("\e[0m_yn"); } else if (!(y % 10)) { printf("\e[0m‾%,u", y); } } printf("\e[0m\n"); } static dontinline void *DeblinterlaceRgba2(unsigned yn, unsigned xn, unsigned char D[4][yn][xn], const unsigned char S[yn][xn][4]) { unsigned y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { D[0][y][x] = S[y][x][0]; D[1][y][x] = S[y][x][1]; D[2][y][x] = S[y][x][2]; D[3][y][x] = S[y][x][3]; } } return D; } void ProcessImageBilinearImpl(unsigned dyn, unsigned dxn, unsigned char dst[4][dyn][dxn], unsigned syn, unsigned sxn, unsigned char src[4][syn][sxn], unsigned char img[syn][sxn][4]) { DeblinterlaceRgba2(syn, sxn, src, img); BilinearScale(4, dyn, dxn, dst, 4, syn, sxn, src, 0, 4, dyn, dxn, syn, sxn, r_, r_, 0, 0); PrintImage2(dyn, dxn, dst, dyn, dxn); } void ProcessImageBilinear(unsigned yn, unsigned xn, unsigned char img[yn][xn][4]) { unsigned dyn, dxn; dyn = lround(yn / r_); dxn = lround(xn / r_); ProcessImageBilinearImpl(dyn, dxn, gc(xmalloc(dyn * dxn * 4)), yn, xn, gc(xmalloc(yn * xn * 4)), img); } static void *b2f(long n, float dst[n], const unsigned char src[n]) { long i; float f; for (i = 0; i < n; ++i) { f = src[i]; f *= 1 / 255.; dst[i] = f; } return dst; } static void *f2b(long n, unsigned char dst[n], const float src[n]) { int x; long i; for (i = 0; i < n; ++i) { x = lroundf(src[i] * 255); dst[i] = MIN(255, MAX(0, x)); } return dst; } void ProcessImageGyarados(unsigned yn, unsigned xn, unsigned char img[yn][xn][4]) { unsigned dyn, dxn; dyn = lround(yn / r_); dxn = lround(xn / r_); PrintImage2( dyn, dxn, EzGyarados(4, dyn, dxn, gc(xmalloc(dyn * dxn * 4)), 4, yn, xn, DeblinterlaceRgba2(yn, xn, gc(xmalloc(yn * xn * 4)), img), 0, 4, dyn, dxn, yn, xn, r_, r_, 0, 0), dyn, dxn); } void MagikarpDecimate(int yw, int xw, unsigned char img[4][yw][xw], int yn, int xn, int n) { int c; if (n <= 1) { PrintImage2(yw, xw, img, yn, xn); } else { for (c = 0; c < 4; ++c) Magikarp2xY(yw, xw, img[c], yn, xn); for (c = 0; c < 4; ++c) Magikarp2xX(yw, xw, img[c], (yn + 1) / 2, xn); MagikarpDecimate(yw, xw, img, (yn + 1) / 2, (xn + 1) / 2, (n + 1) / 2); } } void ProcessImageMagikarp(unsigned yn, unsigned xn, unsigned char img[yn][xn][4]) { MagikarpDecimate(yn, xn, DeblinterlaceRgba2(yn, xn, gc(xmalloc(yn * xn * 4)), img), yn, xn, lround(r_)); } dontinline void WithImageFile(const char *path, void fn(unsigned yn, unsigned xn, unsigned char img[yn][xn][4])) { struct stat st; int fd, yn, xn; void *map, *data; CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_GT(st.st_size, 0); CHECK_LE(st.st_size, INT_MAX); fadvise(fd, 0, 0, MADV_WILLNEED | MADV_SEQUENTIAL); CHECK_NE(MAP_FAILED, (map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))); CHECK_NOTNULL( (data = stbi_load_from_memory(map, st.st_size, &xn, &yn, NULL, 4)), "%s", path); CHECK_NE(-1, munmap(map, st.st_size)); CHECK_NE(-1, close(fd)); fn(yn, xn, data); free(data); } int main(int argc, char *argv[]) { int i, opt; bool bilinear; void (*scaler)(unsigned yn, unsigned xn, unsigned char[yn][xn][4]) = ProcessImageMagikarp; r_ = 2; while ((opt = getopt(argc, argv, "mlsSybr:")) != -1) { switch (opt) { case 'r': r_ = strtod(optarg, NULL); break; case 'm': scaler = ProcessImageMagikarp; break; case 's': case 'S': scaler = ProcessImageGyarados; break; case 'b': scaler = ProcessImageBilinear; break; default: break; } } ShowCrashReports(); for (i = optind; i < argc; ++i) { WithImageFile(argv[i], scaler); } return 0; }
21,177
643
jart/cosmopolitan
false
cosmopolitan/tool/viz/rgbtoxterm.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 "dsp/tty/quant.h" #include "libc/calls/calls.h" #include "libc/log/check.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "third_party/getopt/getopt.h" #define kUsage \ "Usage:\n\ \n\ %s [-cber] [-o FILE] [ARGS...]\n\ \n\ Flags:\n\ \n\ -e enable emphasis\n\ -b emit as background color\n\ -r print raw codes\n\ -c emit cleanup (reset) codes when done\n\ -o FILE redirects output [default: /dev/stdout]\n\ \n\ Arguments:\n\ \n\ - may be passed via ARGS or STDIN (one per line)\n\ - may be #RRGGBB or RRGGBB\n\ - may be #RGB or RGB (#123 → #112233)\n\ - anything else is printed verbatim\n\ \n" static FILE *fout_; static size_t linecap_; static char *outpath_, *line_; static bool rawmode_, background_, emphasis_, cleanup_; wontreturn void usage(int rc, FILE *f) { fprintf(f, kUsage, program_invocation_name); exit(rc); } void getopts(int *argc, char *argv[]) { int opt; outpath_ = "-"; while ((opt = getopt(*argc, argv, "?hrecbo:")) != -1) { switch (opt) { case 'r': rawmode_ = true; break; case 'b': background_ = true; break; case 'c': cleanup_ = true; break; case 'e': emphasis_ = true; break; case 'o': outpath_ = optarg; break; case '?': case 'h': usage(EXIT_SUCCESS, stdout); default: usage(EX_USAGE, stderr); } } } void processarg(const char *arg) { const char *p; size_t r, g, b; if (*(p = arg) == '#') p++; if (strlen(p) == 3 && (isxdigit(p[0]) && isxdigit(p[1]) && isxdigit(p[2]))) { r = hextoint(p[0]) << 4 | hextoint(p[0]); g = hextoint(p[1]) << 4 | hextoint(p[1]); b = hextoint(p[2]) << 4 | hextoint(p[2]); } else if (strlen(p) == 6 && (isxdigit(p[0]) && isxdigit(p[1]) && isxdigit(p[2]) && isxdigit(p[3]) && isxdigit(p[4]) && isxdigit(p[5]))) { r = hextoint(p[0]) << 4 | hextoint(p[1]); g = hextoint(p[2]) << 4 | hextoint(p[3]); b = hextoint(p[4]) << 4 | hextoint(p[5]); } else { fputs(arg, fout_); return; } fprintf(fout_, "%s[%s%d;5;%hhum%s", rawmode_ ? "\e" : "\\e", emphasis_ ? "1;" : "", background_ ? 48 : 38, rgb2tty(r, g, b).xt, &"\n"[rawmode_]); } int main(int argc, char *argv[]) { size_t i; getopts(&argc, argv); CHECK_NOTNULL((fout_ = fopen(outpath_, "w"))); if (optind < argc) { for (i = optind; i < argc; ++i) { processarg(argv[i]); } } else { while ((getline(&line_, &linecap_, stdin)) != -1) { processarg(_chomp(line_)); } free(line_); line_ = 0; } if (cleanup_) { fprintf(fout_, "%s[0m\n", rawmode_ ? "\e" : "\\e"); } CHECK_NE(-1, fclose(fout_)); fout_ = 0; return 0; }
4,817
136
jart/cosmopolitan
false
cosmopolitan/tool/viz/fold.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/errno.h" #include "libc/fmt/conv.h" #include "libc/intrin/safemacros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" int column_; wontreturn void usage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(" [-w COLS] [FILE...]\n", f); exit(rc); } void getopts(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "?hw:")) != -1) { switch (opt) { case 'w': column_ = strtol(optarg, NULL, 0); break; case '?': case 'h': usage(EXIT_SUCCESS, stdout); default: usage(EX_USAGE, stderr); } } if (column_ <= 0) { column_ = 64; } } void fold(FILE *fin, FILE *fout) { unsigned column = 0; for (;;) { wint_t wc = fgetwc(fin); if (wc != -1) { fputwc(wc, fout); if (wc == '\n') { column = 0; } else if (++column == column_) { fputc('\n', fout); column = 0; } } else { if (feof(fin)) { return; } else { fprintf(stderr, "%s: %d\n", "fgetwc", errno); exit(1); } } } } int main(int argc, char *argv[]) { getopts(argc, argv); fold(stdin, stdout); return 0; }
3,205
85
jart/cosmopolitan
false
cosmopolitan/tool/viz/printvideo.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 "dsp/core/core.h" #include "dsp/core/half.h" #include "dsp/core/illumination.h" #include "dsp/mpeg/mpeg.h" #include "dsp/scale/scale.h" #include "dsp/tty/quant.h" #include "dsp/tty/tty.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/framebufferfixedscreeninfo.h" #include "libc/calls/struct/framebuffervirtualscreeninfo.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/itimerval.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/termios.h" #include "libc/calls/ucontext.h" #include "libc/dns/dns.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/xchg.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/alg.h" #include "libc/mem/arraylist.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/bench.h" #include "libc/nexgen32e/x86feature.h" #include "libc/nt/console.h" #include "libc/nt/runtime.h" #include "libc/runtime/buffer.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/internal.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/str/unicode.h" #include "libc/sysv/consts/af.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/f.h" #include "libc/sysv/consts/fd.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/ipproto.h" #include "libc/sysv/consts/itimer.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/mlock.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/ok.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/prio.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/shut.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/splice.h" #include "libc/sysv/consts/termios.h" #include "libc/sysv/consts/w.h" #include "libc/sysv/errfuns.h" #include "libc/time/time.h" #include "libc/x/xsigaction.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image_resize.h" #include "tool/viz/lib/graphic.h" #include "tool/viz/lib/knobs.h" #include "tool/viz/lib/ycbcr.h" /** * @fileoverview MPEG Video Player for Terminal. */ #define GAMMADELTA 0.1 #define NETBUFSIZ (2 * 1024 * 1024) #define MAX_FRAMERATE (1 / 60.) #define USAGE \ " [FLAGS] MPG\n\ Renders motion picture to teletypewriters.\n\ \n\ Flags & Keyboard Shortcuts:\n\ -s stats\n\ -t true color\n\ -d dithering\n\ -3 ibm cp437 rendering\n\ -4 unicode rendering\n\ -a ansi quantization\n\ -x xterm256 quantization\n\ -A assume ansi ansi palette\n\ -T assume tango ansi palette\n\ -v increases verbosity [flag]\n\ -L PATH redirects stderr to path [flag]\n\ -y yes to interactive prompts [flag]\n\ -h shows this information [flag]\n\ UP/DOWN adjust volume [keyboard]\n\ CTRL+L redraw [keyboard]\n\ CTRL+Z suspend [keyboard]\n\ CTRL+C exit [keyboard]\n\ q quit [keyboard]\n\ \n\ Effects Shortcuts:\n\ \n\ S Toggle Swing (TV, PC)\n\ Y Toggle Black/White Mode\n\ p Toggle Primaries (BT.601, BT.709)\n\ g +Gamma G -Gamma\n\ l +Illumination L -Illumination\n\ k +LumaKernel K -LumaKernel\n\ j +ChromaKernel J -ChromaKernel\n\ CTRL-G {Unsharp,Sharp}\n\ \n\ Environment Variables:\n\ SOX overrides location of SoX executable\n\ FFPLAY overrides location of FFmpeg ffplay executable\n\ ROWS=𝑦 sets height [inarticulate mode]\n\ COLUMNS=𝑥 sets width [inarticulate mode]\n\ TERM=dumb inarticulate mode\n\ \n\ Notes:\n\ \n\ Your video printer natively supports .mpg files. If your videos are\n\ in a different format, then it's fast and easy to convert them:\n\ \n\ ffmpeg -i movie.mkv movie.mpg\n\ \n\ The terminal fonts we recommend are PragmataPro, Bitstream Vera Sans\n\ Mono (known as DejaVu Sans Mono in the open source community), Menlo,\n\ and Lucida Console.\n\ \n\ On Linux, playing audio requires either `sox` or `ffplay` being on\n\ the $PATH. Kitty is the fastest terminal. Alacritty also has a fast\n\ display. GNOME Terminal and xterm both work well in 256-color or ANSI\n\ mode.\n\ \n" #define CTRL(C) ((C) ^ 0100) #define ALT(C) ((033 << 010) | (C)) #define ARGZ(...) ((char *const[]){__VA_ARGS__, NULL}) #define MOD(X, Y) ((X) - (ABS(Y)) * ((X) / ABS(Y))) #define BALLOC(B, A, N, NAME) \ ({ \ INFOF("balloc/%s %,zu bytes", NAME, N); \ balloc(B, A, N); \ }) #define TIMEIT(OUT_NANOS, FORM) \ do { \ long double Start = nowl(); \ FORM; \ (OUT_NANOS) = (uint64_t)((nowl() - Start) * 1e9L); \ } while (0) typedef bool (*openspeaker_f)(void); enum Sharp { kSharpNone, kSharpUnsharp, kSharpSharp, kSharpMAX, }; enum Blur { kBlurNone, kBlurBox, kBlurGaussian, kBlurMAX, }; struct NamedVector { char name[8]; const double (*vector)[3]; }; struct VtFrame { size_t i, n; union { struct GuardedBuffer b; char *bytes; }; }; struct FrameCountRing { size_t i, n; float p[64]; /* seconds relative to starttime_ */ }; struct FrameBuffer { void *map; size_t size; char *path; int fd; struct FrameBufferFixedScreenInfo fscreen; struct FrameBufferVirtualScreenInfo vscreen; }; static const struct itimerval kTimerDisarm = { {0, 0}, {0, 0}, }; static const struct itimerval kTimerHalfSecondSingleShot = { {0, 0}, {0, 500000}, }; static const struct NamedVector kPrimaries[] = { {"BT.601", &kBt601Primaries}, {"BT.709", &kBt709Primaries}, }; static const struct NamedVector kLightings[] = { {"A", &kIlluminantA}, {"C", &kIlluminantC}, {"D50", &kIlluminantD50}, {"D55", &kIlluminantD55}, {"D65", &kIlluminantD65}, {"D75", &kIlluminantD75}, {"F2", &kIlluminantF2}, {"F7", &kIlluminantF7}, {"F11", &kIlluminantF11}, {"A-10", &kIlluminantAD10}, {"C-10", &kIlluminantCD10}, {"D50-10", &kIlluminantD50D10}, {"D55-10", &kIlluminantD55D10}, {"D65-10", &kIlluminantD65D10}, {"D75-10", &kIlluminantD75D10}, {"F2-10", &kIlluminantF2D10}, {"F7-10", &kIlluminantF7D10}, {"F11-10", &kIlluminantF11D10}, }; static plm_t *plm_; static float gamma_; static int volscale_; static enum Blur blur_; static enum Sharp sharp_; static jmp_buf jb_, jbi_; static double pary_, parx_; static struct TtyIdent ti_; static struct YCbCr *ycbcr_; static bool emboss_, sobel_; static volatile int playpid_; static struct winsize wsize_; static float hue_, sat_, lit_; static struct FrameBuffer fb0_; static unsigned chans_, srate_; static volatile bool ignoresigs_; static size_t dh_, dw_, framecount_; static struct FrameCountRing fcring_; static volatile bool resized_, piped_; static int lumakernel_, chromakernel_; static openspeaker_f tryspeakerfns_[4]; static int primaries_, lighting_, swing_; static uint64_t t1, t2, t3, t4, t5, t6, t8; static const char *sox_, *ffplay_, *patharg_; static struct GuardedBuffer xtcodes_, audio_; static struct VtFrame vtframe_[2], *f1_, *f2_; static struct Graphic graphic_[2], *g1_, *g2_; static bool yes_, stats_, dither_, ttymode_, istango_; static long double deadline_, dura_, skip_, starttime_; static long double decode_start_, f1_start_, f2_start_; static int16_t pcm_[PLM_AUDIO_SAMPLES_PER_FRAME * 2 / 8][8]; static int16_t pcmscale_[PLM_AUDIO_SAMPLES_PER_FRAME * 2 / 8][8]; static bool fullclear_, historyclear_, tuned_, yonly_, gotvideo_; static int homerow_, lastrow_, playfd_, infd_, outfd_, nullfd_, speakerfails_; static char host_[DNS_NAME_MAX + 1], status_[7][200], logpath_[PATH_MAX], fifopath_[PATH_MAX], chansstr_[32], sratestr_[32], port_[32]; static void OnCtrlC(void) { longjmp(jb_, 1); } static void OnResize(void) { resized_ = true; } static void OnSigPipe(void) { piped_ = true; } static void OnSigChld(void) { playpid_ = 0, piped_ = true; } static void StrikeDownCrapware(int sig) { kill(playpid_, SIGKILL); } static long AsMilliseconds(long double ts) { return rintl(ts * 1e3); } static long AsNanoseconds(long double ts) { return rintl(ts * 1e9); } static long double GetGraceTime(void) { return deadline_ - nowl(); } static int GetNamedVector(const struct NamedVector *choices, size_t n, const char *s) { int i; char name[sizeof(choices->name)]; strncpy(name, s, sizeof(name)); strntoupper(name, sizeof(name)); for (i = 0; i < n; ++i) { if (memcmp(choices[i].name, name, sizeof(name)) == 0) { return i; } } return -1; } static int GetPrimaries(const char *s) { return GetNamedVector(kPrimaries, ARRAYLEN(kPrimaries), s); } static int GetLighting(const char *s) { return GetNamedVector(kLightings, ARRAYLEN(kLightings), s); } static bool CloseSpeaker(void) { int rc, wstatus; rc = 0; sched_yield(); if (playfd_) { rc |= close(playfd_); playfd_ = -1; } if (playpid_) { kill(playpid_, SIGTERM); xsigaction(SIGALRM, StrikeDownCrapware, SA_RESETHAND, 0, 0); setitimer(ITIMER_REAL, &kTimerHalfSecondSingleShot, NULL); while (playpid_) { if (waitpid(playpid_, &wstatus, 0) != -1) { rc |= WEXITSTATUS(wstatus); } else if (errno == EINTR) { continue; } else { rc = -1; } break; } playpid_ = 0; setitimer(ITIMER_REAL, &kTimerDisarm, NULL); } return !!rc; } static void ResizeVtFrame(struct VtFrame *f, size_t yn, size_t xn) { BALLOC(&f->b, PAGESIZE, 64 + yn * (xn * 32 + 8), __FUNCTION__); f->i = f->n = 0; } static void RecordFactThatFrameWasFullyRendered(void) { fcring_.p[fcring_.i] = nowl() - starttime_; fcring_.n += 1; fcring_.i += 1; fcring_.i &= ARRAYLEN(fcring_.p) - 1; } static double MeasureFrameRate(void) { int i, j, n, m; if (fcring_.n) { m = ARRAYLEN(fcring_.p); n = MIN(fcring_.n, m); i = (fcring_.i - 1) & (m - 1); j = (fcring_.i - n) & (m - 1); return n / (fcring_.p[i] - fcring_.p[j]); } else { return 0; } } static bool ShouldUseFrameBuffer(void) { return fb0_.fd != -1; } static bool IsHighDefinition(long yn, long xn) { return yn * xn >= 1280 * 720; } static void ComputeColoringSolution(void) { YCbCrInit(&ycbcr_, yonly_, swing_, gamma_, *kPrimaries[primaries_].vector, *kLightings[lighting_].vector); } static void DimensionDisplay(void) { size_t yn, xn; double ratio, height, width; do { resized_ = false; if (ShouldUseFrameBuffer()) { pary_ = 1; parx_ = 1; dh_ = fb0_.vscreen.yres; dw_ = fb0_.vscreen.xres; wsize_.ws_row = fb0_.vscreen.yres_virtual; wsize_.ws_col = fb0_.vscreen.xres_virtual; } else { pary_ = 1; parx_ = 1; wsize_.ws_row = 25; wsize_.ws_col = 80; wsize_ = (struct winsize){.ws_row = 40, .ws_col = 80}; if (_getttysize(outfd_, &wsize_) == -1) _getttysize(0, &wsize_); dh_ = wsize_.ws_row * 2; dw_ = wsize_.ws_col * 2; } ratio = g1_->xn; ratio /= g1_->yn; height = dh_; width = dw_; height = MIN(height, height * ratio); width = MIN(width, width * ratio); yn = height; xn = width; yn = ROUNDDOWN(yn, 2); xn = ROUNDDOWN(xn, 2); g2_ = resizegraphic(&graphic_[1], yn, xn); INFOF("%s 𝑑(%hu×%hu)×(%d,%d): 𝑔₁(%zu×%zu,r=%f) → 𝑔₂(%zu×%zu)", "DimensionDisplay", wsize_.ws_row, wsize_.ws_col, g1_->yn, g1_->xn, ratio, yn, xn); BALLOC(&xtcodes_, 64, ((g2_->yn) * g2_->xn + 8) * sizeof(struct TtyRgb), "xtcodes_"); ResizeVtFrame(&vtframe_[0], (g2_->yn), g2_->xn); ResizeVtFrame(&vtframe_[1], (g2_->yn), g2_->xn); f1_ = &vtframe_[0]; f2_ = &vtframe_[1]; if (ttymode_) { homerow_ = MIN(wsize_.ws_row - HALF(g2_->yn), HALF(wsize_.ws_row - HALF(g2_->yn))); } lastrow_ = homerow_ + HALF(g2_->yn); ComputeColoringSolution(); } while (resized_); } static int WriteAudio(int fd, const void *data, size_t size, int deadlinems) { ssize_t rc; const char *p; size_t wrote, n; p = data; n = size; do { TryAgain: if ((rc = write(fd, p, n)) != -1) { wrote = rc; p += wrote; n -= wrote; } else if (errno == EINTR) { goto TryAgain; } else if (errno == EAGAIN) { if (poll((struct pollfd[]){{fd, POLLOUT}}, 1, deadlinems) == 0) { return etimedout(); } } else { return -1; } } while (n); return 0; } static bool TrySpeaker(const char *prog, char *const *args) { int pipefds[2]; CHECK_NE(-1, pipe2(pipefds, O_CLOEXEC)); if (!(playpid_ = fork())) { dup2(pipefds[0], 0); dup2(fileno(__log_file), 1); dup2(fileno(__log_file), 2); close(fileno(__log_file)); execv(prog, args); abort(); } playfd_ = pipefds[1]; return true; } static bool TrySox(void) { return TrySpeaker(sox_, ARGZ("play", "-q", "-c", chansstr_, "-traw", "-esigned", "-b16", "-r", sratestr_, "-")); } static bool TryFfplay(void) { return TrySpeaker(ffplay_, ARGZ("ffplay", "-nodisp", "-loglevel", "quiet", "-fflags", "nobuffer", "-ac", chansstr_, "-ar", sratestr_, "-f", "s16le", "pipe:")); } static bool OpenSpeaker(void) { size_t i; static bool once, count; if (!once) { once = true; i = 0; if (ffplay_) tryspeakerfns_[i++] = TryFfplay; if (sox_) tryspeakerfns_[i++] = TrySox; } snprintf(fifopath_, sizeof(fifopath_), "%s%s.%d.%d.wav", kTmpPath, firstnonnull(program_invocation_short_name, "unknown"), getpid(), count); for (i = 0; i < ARRAYLEN(tryspeakerfns_); ++i) { if (tryspeakerfns_[i]) { if (++speakerfails_ <= 2 && tryspeakerfns_[i]()) { return true; } else { speakerfails_ = 0; tryspeakerfns_[i] = NULL; } } } return false; } static void OnAudio(plm_t *mpeg, plm_samples_t *samples, void *user) { if (playfd_ != -1) { DEBUGF("OnAudio() [grace=%,ldns]", AsNanoseconds(GetGraceTime())); CHECK_EQ(2, chans_); CHECK_EQ(ARRAYLEN(pcm_) * 8, samples->count * chans_); float2short(ARRAYLEN(pcm_), pcm_, (void *)samples->interleaved); scalevolume(ARRAYLEN(pcm_), pcm_, volscale_); sad16x8n(ARRAYLEN(pcm_), pcm_, pcmscale_); DEBUGF("transcoded audio"); TryAgain: if (WriteAudio(playfd_, pcm_, sizeof(pcm_), 1000) != -1) { DEBUGF("WriteAudio(%d, %zu) ok [grace=%,ldns]", playfd_, samples->count * 2, AsNanoseconds(GetGraceTime())); } else { WARNF("WriteAudio(%d, %zu) failed: %s", playfd_, samples->count * 2, strerror(errno)); CloseSpeaker(); if (OpenSpeaker()) { goto TryAgain; } } } } static void DescribeAlgorithms(char *p) { if (dither_ && TTYQUANT()->alg != kTtyQuantTrue) { p = stpcpy(p, " ℍithered"); } if (yonly_) { p = stpcpy(p, " grayscaled"); } p += sprintf(p, " magikarp:%d:%d", lumakernel_, chromakernel_); switch (TTYQUANT()->alg) { case kTtyQuantTrue: p = stpcpy(p, " true-color"); break; case kTtyQuantXterm256: p = stpcpy(p, " xterm256"); break; case kTtyQuantAnsi: p = stpcpy(p, " aixterm ansi"); if (istango_) p = stpcpy(p, " tango"); break; default: break; } switch (TTYQUANT()->blocks) { case kTtyBlocksCp437: p = stpcpy(p, " ibm cp437"); break; case kTtyBlocksUnicode: p = stpcpy(p, " unicode"); break; default: break; } *p++ = ' '; *p = '\0'; } static char *StartRender(char *vt) { if (!ttymode_) vt += sprintf(vt, "\r\n\r\n"); if (fullclear_) { vt += sprintf(vt, "\e[0m\e[H\e[J"); fullclear_ = false; } else if (historyclear_) { vt += sprintf(vt, "\e[0m\e[H\e[J\e[3J"); historyclear_ = false; } vt += sprintf(vt, "\e[%hhuH", homerow_ + 1); return vt; } static void EndRender(char *vt) { vt += sprintf(vt, "\e[0m"); f2_->n = (intptr_t)vt - (intptr_t)f2_->b.p; f2_->i = 0; } static bool IsNonZeroFloat(float f) { return fabsf(f) > 0.001f; } static bool HasAdjustments(void) { return (IsNonZeroFloat(hue_) || IsNonZeroFloat(sat_) || IsNonZeroFloat(lit_)) || (emboss_ || sharp_ || blur_ || sobel_ || pf1_ || pf2_ || pf3_ || pf4_ || pf5_ || pf6_ || pf7_ || pf8_ || pf9_ || pf10_ || pf11_ || pf12_); } static char *DescribeAdjustments(char *p) { if (emboss_) p = stpcpy(p, " emboss"); if (sobel_) p = stpcpy(p, " sobel"); switch (sharp_) { case kSharpSharp: p = stpcpy(p, " sharp"); break; case kSharpUnsharp: p = stpcpy(p, " unsharp"); break; default: break; } switch (blur_) { case kBlurBox: p = stpcpy(p, " boxblur"); break; case kBlurGaussian: p = stpcpy(p, " gaussian"); break; default: break; } if (IsNonZeroFloat(hue_)) p += sprintf(p, " hue%+.2f", hue_); if (IsNonZeroFloat(sat_)) p += sprintf(p, " sat%+.2f", sat_); if (IsNonZeroFloat(lit_)) p += sprintf(p, " lit%+.2f", lit_); if (pf1_) p = stpcpy(p, " PF1"); if (pf2_) p = stpcpy(p, " PF2"); if (pf3_) p = stpcpy(p, " PF3"); if (pf4_) p = stpcpy(p, " PF4"); if (pf5_) p = stpcpy(p, " PF5"); if (pf6_) p = stpcpy(p, " PF6"); if (pf7_) p = stpcpy(p, " PF7"); if (pf8_) p = stpcpy(p, " PF8"); if (pf9_) p = stpcpy(p, " PF9"); if (pf10_) p = stpcpy(p, " PF10"); if (pf11_) p = stpcpy(p, " PF11"); if (pf12_) p = stpcpy(p, " PF12"); *p++ = ' '; *p++ = '\0'; return p; } static const char *DescribeSwing(int swing) { switch (swing) { case 219: return "TV"; case 255: return "PC"; default: return "??"; } } static void RenderIt(void) { long bpf; double bpc; char *vt, *p; unsigned yn, xn; struct TtyRgb bg, fg; yn = g2_->yn; xn = g2_->xn; vt = f2_->b.p; p = StartRender(vt); if (TTYQUANT()->alg == kTtyQuantTrue) { bg = (struct TtyRgb){0, 0, 0, 0}; fg = (struct TtyRgb){0xee, 0xff, 0xff, 0}; p = stpcpy(p, "\e[48;2;0;0;0;38;2;255;255;255m"); } else if (TTYQUANT()->alg == kTtyQuantAnsi) { bg = g_ansi2rgb_[0]; fg = g_ansi2rgb_[7]; p += sprintf(p, "\e[%d;%dm", 30 + g_ansi2rgb_[0].xt, 40 + g_ansi2rgb_[7].xt); } else { bg = (struct TtyRgb){0, 0, 0, 16}; fg = (struct TtyRgb){0xff, 0xff, 0xff, 231}; p = stpcpy(p, "\e[48;5;16;38;5;231m"); } p = ttyraster(p, xtcodes_.p, yn, xn, bg, fg); if (ttymode_ && stats_) { bpc = bpf = p - vt; bpc /= wsize_.ws_row * wsize_.ws_col; sprintf(status_[4], " %s/%s/%s %d×%d → %u×%u pixels ", kPrimaries[primaries_].name, DescribeSwing(swing_), kLightings[lighting_].name, plm_get_width(plm_), plm_get_height(plm_), g2_->xn, g2_->yn); sprintf(status_[5], " decode:%,8luµs | magikarp:%,8luµs ", plmpegdecode_latency_, magikarp_latency_); sprintf(status_[1], " ycbcr2rgb:%,8luµs | gyarados:%,8luµs ", ycbcr2rgb_latency_, gyarados_latency_); sprintf(status_[0], " fx:%,ldµs %.6fbpc %,ldbpf %.6ffps ", lroundl(t6 / 1e3L), bpc, bpf, (size_t)(p - vt), MeasureFrameRate()); sprintf(status_[2], " gamma:%.1f %hu columns × %hu lines of text ", gamma_, wsize_.ws_col, wsize_.ws_row); DescribeAlgorithms(status_[3]); p += sprintf(p, "\e[0m"); if (HasAdjustments()) { DescribeAdjustments(status_[6]); p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 7, HALF(xn) - strwidth(status_[6], 0), status_[6]); } p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 6, HALF(xn) - strwidth(status_[4], 0), status_[4]); p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 5, HALF(xn) - strwidth(status_[5], 0), status_[5]); p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 4, HALF(xn) - strwidth(status_[1], 0), status_[1]); p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 3, HALF(xn) - strwidth(status_[0], 0), status_[0]); p += sprintf(p, "\e[%d;%dH%30s", lastrow_ - 2, HALF(xn) - strwidth(status_[2], 0), status_[2]); p += sprintf(p, "\e[%d;%dH%s", lastrow_ - 1, HALF(xn) - strwidth(status_[3], 0), status_[3]); p += sprintf(p, "\e[%d;%dH %s %s ", lastrow_ - 2, 2, program_invocation_name, ""); p += sprintf(p, "\e[%d;%dH %s ", lastrow_ - 1, 2, "by justine tunney <[email protected]>"); } EndRender(p); } static void RasterIt(void) { static bool once; static void *buf; if (!once) { buf = _mapanon(ROUNDUP(fb0_.size, FRAMESIZE)); once = true; } WriteToFrameBuffer(fb0_.vscreen.yres_virtual, fb0_.vscreen.xres_virtual, buf, g2_->yn, g2_->xn, g2_->b.p, fb0_.vscreen.yres, fb0_.vscreen.xres); memcpy(fb0_.map, buf, fb0_.size); } static void TranscodeVideo(plm_frame_t *pf) { CHECK_EQ(pf->cb.width, pf->cr.width); CHECK_EQ(pf->cb.height, pf->cr.height); DEBUGF("TranscodeVideo() [grace=%,ldns]", AsNanoseconds(GetGraceTime())); g2_ = &graphic_[1]; t5 = 0; TIMEIT(t1, { pary_ = 2; if (pf1_) pary_ = 1.; if (pf2_) pary_ = (266 / 64.) * (900 / 1600.); pary_ *= plm_get_pixel_aspect_ratio(plm_); YCbCr2RgbScale(g2_->yn, g2_->xn, g2_->b.p, pf->y.height, pf->y.width, (void *)pf->y.data, pf->cr.height, pf->cr.width, (void *)pf->cb.data, (void *)pf->cr.data, pf->y.height, pf->y.width, pf->cr.height, pf->cr.width, pf->height, pf->width, pary_, parx_, &ycbcr_); }); t2 = 0; t8 = 0; TIMEIT(t6, { switch (blur_) { case kBlurBox: boxblur(g2_); break; case kBlurGaussian: gaussian(g2_->yn, g2_->xn, g2_->b.p); break; default: break; } if (sobel_) sobel(g2_); if (emboss_) emboss(g2_); switch (sharp_) { case kSharpSharp: sharpen(3, g2_->yn, g2_->xn, g2_->b.p, g2_->yn, g2_->xn); break; case kSharpUnsharp: unsharp(3, g2_->yn, g2_->xn, g2_->b.p, g2_->yn, g2_->xn); break; default: break; } if (dither_ && TTYQUANT()->alg != kTtyQuantTrue) { dither(g2_->yn, g2_->xn, g2_->b.p, g2_->yn, g2_->xn); } }); if (ShouldUseFrameBuffer()) { t3 = 0; TIMEIT(t4, RasterIt()); } else { TIMEIT(t3, getxtermcodes(xtcodes_.p, g2_)); TIMEIT(t4, RenderIt()); } INFOF("𝑓%zu(%u×%u) %,zub (%f BPP) " "ycbcr=%,zuns " "scale=%,zuns " "lace=%,zuns " "fx=%,zuns " "quantize=%,zuns " "render=%,zuns", framecount_++, g2_->yn, g2_->xn, f2_->n, (f1_->n / (double)(g2_->yn * g2_->xn)), t1, t2, t8, t6, t3, t4); } static void OnVideo(plm_t *mpeg, plm_frame_t *pf, void *user) { gotvideo_ = true; if (f2_->n) { WARNF("video frame dropped"); } else { TranscodeVideo(pf); if (!f1_->n) { xchg(&f1_, &f2_); f1_start_ = decode_start_; } else { f2_start_ = decode_start_; } } } static void OpenVideo(void) { size_t yn, xn; playfd_ = -1; INFOF("%s(%`'s)", "OpenVideo", patharg_); CHECK_NOTNULL((plm_ = plm_create_with_filename(patharg_))); swing_ = 219; xn = plm_get_width(plm_); yn = plm_get_height(plm_); lighting_ = GetLighting("D65"); primaries_ = IsHighDefinition(yn, xn) ? GetPrimaries("BT.709") : GetPrimaries("BT.601"); plm_set_video_decode_callback(plm_, OnVideo, NULL); plm_set_audio_decode_callback(plm_, OnAudio, NULL); plm_set_loop(plm_, false); FormatInt64(chansstr_, (chans_ = 2)); FormatInt64(sratestr_, (srate_ = plm_get_samplerate(plm_))); if (plm_get_num_audio_streams(plm_) && OpenSpeaker()) { plm_set_audio_enabled(plm_, true, 0); } else { plm_set_audio_enabled(plm_, false, 0); } g2_ = g1_ = resizegraphic(&graphic_[0], yn, xn); } static ssize_t WriteVideoCall(void) { size_t amt; ssize_t rc; amt = min(PAGESIZE * 4, f1_->n - f1_->i); if ((rc = write(outfd_, f1_->bytes + f1_->i, amt)) != -1) { if ((f1_->i += rc) == f1_->n) { if (plm_get_audio_enabled(plm_)) { plm_set_audio_lead_time( plm_, MAX(0, MIN(nowl() - f1_start_, plm_get_samplerate(plm_) / PLM_AUDIO_SAMPLES_PER_FRAME))); } f1_start_ = f2_start_; f1_->i = f1_->n = 0; xchg(&f1_, &f2_); RecordFactThatFrameWasFullyRendered(); } } return rc; } static void DrainVideo(void) { if (f1_ && f1_->n) { ttywrite(outfd_, f1_->bytes + f1_->i, f1_->n - f1_->i); f1_->i = f1_->n = 0; } if (f2_ && f2_->n) { f2_->i = f2_->n = 0; } } static void WriteVideo(void) { ssize_t rc; DEBUGF("write(tty) grace=%,ldns", AsNanoseconds(GetGraceTime())); if ((rc = WriteVideoCall()) != -1) { DEBUGF("write(tty) → %zd [grace=%,ldns]", rc, AsNanoseconds(GetGraceTime())); } else if (errno == EAGAIN || errno == EINTR) { DEBUGF("write(tty) → EINTR"); longjmp(jbi_, 1); } else if (errno == EPIPE) { DEBUGF("write(tty) → EPIPE"); longjmp(jb_, 1); } else { FATALF("write(tty) → %s", strerror(errno)); } } static void RefreshDisplay(void) { if (f1_ && f1_->n) f1_->i = 0; DimensionDisplay(); resized_ = false; historyclear_ = true; ttysend(outfd_, "\e[0m\e[H\e[3J"); } static void SetQuant(enum TtyQuantizationAlgorithm alg, enum TtyQuantizationChannels chans, enum TtyBlocksSelection blocks) { tuned_ = true; ttyquantsetup(alg, chans, blocks); } static void SetQuantizationAlgorithm(enum TtyQuantizationAlgorithm alg) { SetQuant(alg, TTYQUANT()->chans, TTYQUANT()->blocks); /* TODO(jart): autotune */ } static void SetDithering(bool dither) { tuned_ = true; dither_ = dither; } static optimizesize bool ProcessOptKey(int opt) { switch (opt) { case 's': stats_ = !stats_; return true; case '3': TTYQUANT()->blocks = kTtyBlocksCp437; return true; case '4': TTYQUANT()->blocks = kTtyBlocksUnicode; return true; case 'd': SetDithering(!dither_); return true; case 't': SetQuantizationAlgorithm(kTtyQuantTrue); return true; case 'a': SetQuantizationAlgorithm(kTtyQuantAnsi); return true; case 'x': SetQuantizationAlgorithm(kTtyQuantXterm256); return true; case 'A': istango_ = false; memcpy(g_ansi2rgb_, &kCgaPalette, sizeof(kCgaPalette)); return true; case 'T': istango_ = true; memcpy(g_ansi2rgb_, &kTangoPalette, sizeof(kTangoPalette)); return true; default: return false; } } static optimizesize void ReadKeyboard(void) { char b[64]; int c, i, n, sgn; memset(b, -1, sizeof(b)); b[0] = CTRL('B'); /* for eof case */ if ((n = read(infd_, &b, sizeof(b))) != -1) { for (;;) { i = 0; c = b[i++]; if (!ProcessOptKey(c)) { sgn = isupper(c) ? -1 : 1; switch (c) { case 'Y': yonly_ = !yonly_; ComputeColoringSolution(); break; case 'S': swing_ = swing_ == 219 ? 255 : 219; ComputeColoringSolution(); break; case 'p': case 'P': primaries_ = MOD(sgn + primaries_, ARRAYLEN(kPrimaries)); ComputeColoringSolution(); break; case 'l': case 'L': lighting_ = MOD(sgn + lighting_, ARRAYLEN(kLightings)); ComputeColoringSolution(); break; case 'g': case 'G': gamma_ += sgn * GAMMADELTA; g_xterm256_gamma += sgn * GAMMADELTA; ComputeColoringSolution(); break; case 'k': case 'K': lumakernel_ = MOD(sgn + lumakernel_, ARRAYLEN(kMagikarp)); memcpy(g_magikarp, kMagikarp[lumakernel_], sizeof(kMagikarp[0])); break; case 'j': case 'J': chromakernel_ = MOD(sgn + chromakernel_, ARRAYLEN(kMagkern)); memcpy(g_magkern, kMagkern[chromakernel_], sizeof(kMagkern[0])); break; case 'q': case CTRL('C'): longjmp(jb_, 1); break; case CTRL('Z'): ttyshowcursor(outfd_); raise(SIGSTOP); break; case CTRL('G'): sharp_ = (sharp_ + 1) % kSharpMAX; break; case CTRL('\\'): raise(SIGQUIT); break; case CTRL('L'): RefreshDisplay(); break; case '\e': if (n == 1) { longjmp(jb_, 1); /* \e <𝟷𝟶𝟶ms*VTIME> is ESC */ } switch (b[i++]) { case '[': switch (b[i++]) { case 'A': /* "\e[A" is up arrow */ ++volscale_; break; case 'B': /* "\e[B" is down arrow */ --volscale_; break; case 'C': /* "\e[C" is right arrow */ break; case 'D': /* "\e[D" is left arrow */ break; case '1': switch (b[i++]) { case '1': switch (b[i++]) { case '~': /* \e[11~ is F1 */ pf1_ = !pf1_; break; default: break; } break; case '2': switch (b[i++]) { case '~': /* \e[12~ is F2 */ pf2_ = !pf2_; break; default: break; } break; case '3': switch (b[i++]) { case '~': /* \e[13~ is F3 */ pf3_ = !pf3_; break; default: break; } break; case '4': switch (b[i++]) { case '~': /* \e[14~ is F4 */ pf4_ = !pf4_; break; default: break; } break; case '5': switch (b[i++]) { case '~': /* \e[15~ is F5 */ pf5_ = !pf5_; break; default: break; } break; case '7': switch (b[i++]) { case '~': /* \e[17~ is F6 */ pf6_ = !pf6_; break; default: break; } break; case '8': switch (b[i++]) { case '~': /* \e[18~ is F7 */ pf7_ = !pf7_; break; default: break; } break; case '9': switch (b[i++]) { case '~': /* \e[19~ is F8 */ pf8_ = !pf8_; break; default: break; } break; default: break; } break; case '2': switch (b[i++]) { case '0': switch (b[i++]) { case '~': /* \e[20~ is F9 */ pf9_ = !pf9_; break; default: break; } break; case '1': switch (b[i++]) { case '~': /* \e[21~ is F10 */ pf10_ = !pf10_; break; default: break; } break; case '3': switch (b[i++]) { case '~': /* \e[23~ is F11 */ pf11_ = !pf11_; break; default: break; } break; case '4': switch (b[i++]) { case '~': /* \e[24~ is F12 */ pf12_ = !pf12_; break; default: break; } break; default: break; } break; case '[': switch (b[i++]) { case 'A': /* \e[[A is F1 */ pf1_ = !pf1_; break; case 'B': /* \e[[B is F2 */ pf2_ = !pf2_; break; case 'C': /* \e[[C is F3 */ pf3_ = !pf3_; break; case 'D': /* \e[[D is F4 */ pf4_ = !pf4_; break; case 'E': /* \e[[E is F5 */ pf5_ = !pf5_; break; default: break; } break; default: break; } break; case 'O': switch (b[i++]) { case 'P': /* \eOP is F1 */ pf1_ = !pf1_; break; case 'Q': /* \eOQ is F2 */ pf2_ = !pf2_; break; case 'R': /* \eOR is F3 */ pf3_ = !pf3_; break; case 'S': /* \eOS is F4 */ pf4_ = !pf4_; break; case 'T': /* \eOT is F5 */ pf5_ = !pf5_; break; case 'U': /* \eOU is F6 */ pf6_ = !pf6_; break; case 'V': /* \eOV is F7 */ pf7_ = !pf7_; break; case 'W': /* \eOW is F8 */ pf8_ = !pf8_; break; case 'Y': /* \eOY is F10 */ pf10_ = !pf10_; break; case 'Z': /* \eOZ is F11 */ pf11_ = !pf11_; break; case '[': /* \eO[ is F12 */ pf12_ = !pf12_; break; default: break; } break; default: break; } break; default: break; } } if ((n -= i) <= 0) { break; } else { memmove(b, b + i, sizeof(b) - i); } } } else if (errno == EINTR) { longjmp(jbi_, 1); } } static void PerformBestEffortIo(void) { int toto, pollms; struct pollfd fds[] = { {infd_, POLLIN}, {outfd_, f1_ && f1_->n ? POLLOUT : 0}, }; pollms = MAX(0, AsMilliseconds(GetGraceTime())); DEBUGF("poll() ms=%,d", pollms); if ((toto = poll(fds, ARRAYLEN(fds), pollms)) != -1) { DEBUGF("poll() toto=%d [grace=%,ldns]", toto, AsNanoseconds(GetGraceTime())); if (toto) { if (fds[0].revents & (POLLIN | POLLERR)) ReadKeyboard(); if (fds[1].revents & (POLLOUT | POLLERR)) WriteVideo(); } } else if (errno == EINTR) { DEBUGF("poll() → EINTR"); return; } else { FATALF("poll() → %s", strerror(errno)); } } static void RestoreTty(void) { DrainVideo(); if (ttymode_) ttysend(outfd_, "\r\n\e[J"); ttymode_ = false; ttyraw(-1); } static void HandleSignals(void) { if (piped_) { WARNF("SIGPIPE"); CloseSpeaker(); piped_ = false; } if (resized_) { RefreshDisplay(); } } static void PrintVideo(void) { long double decode_last, decode_end, next_tick, lag; dura_ = MIN(MAX_FRAMERATE, 1 / plm_get_framerate(plm_)); INFOF("framerate=%f dura=%f", plm_get_framerate(plm_), dura_); next_tick = deadline_ = decode_last = nowl(); next_tick += dura_; deadline_ += dura_; do { DEBUGF("plm_decode [grace=%,ldns]", AsNanoseconds(GetGraceTime())); decode_start_ = nowl(); plm_decode(plm_, decode_start_ - decode_last); decode_last = decode_start_; decode_end = nowl(); lag = decode_end - decode_start_; while (decode_end + lag > next_tick) next_tick += dura_; deadline_ = next_tick - lag; if (gotvideo_ || !plm_get_video_enabled(plm_)) { gotvideo_ = false; INFOF("entering printvideo event loop (lag=%,ldns, grace=%,ldns)", AsNanoseconds(lag), AsNanoseconds(GetGraceTime())); } do { if (!setjmp(jbi_)) { PerformBestEffortIo(); } HandleSignals(); } while (AsMilliseconds(GetGraceTime()) > 0); } while (plm_ && !plm_has_ended(plm_)); } static bool AskUserYesOrNoQuestion(const char *prompt) { char c; if (yes_ || !ttymode_) return true; ttysend(outfd_, "\r\e[K"); ttysend(outfd_, prompt); ttysend(outfd_, " [yn] "); poll((struct pollfd[]){{infd_, POLLIN}}, 1, -1); c = 0, read(infd_, &c, 1); ttysend(infd_, "\r\e[K"); return c == 'y' || c == 'Y'; } static bool CanPlayAudio(void) { if (ffplay_ || sox_) { return true; } else if (AskUserYesOrNoQuestion( "ffplay not found; continue without audio?")) { return false; } else { longjmp(jb_, 1); } } static void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } static void GetOpts(int argc, char *argv[]) { int opt; snprintf(logpath_, sizeof(logpath_), "%s%s.log", kTmpPath, firstnonnull(program_invocation_short_name, "unknown")); while ((opt = getopt(argc, argv, "?34AGSTVYabdfhnpstxyzvL:")) != -1) { switch (opt) { case 'y': yes_ = true; break; case 'v': ++__log_level; break; case 'L': snprintf(logpath_, sizeof(logpath_), "%s", optarg); break; case 'Y': yonly_ = true; break; case '?': case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: if (!ProcessOptKey(opt)) { PrintUsage(EX_USAGE, stderr); } } } } static void OnExit(void) { if (playpid_) kill(playpid_, SIGTERM), sched_yield(); if (plm_) plm_destroy(plm_), plm_ = NULL; YCbCrFree(&ycbcr_); RestoreTty(); ttyidentclear(&ti_); close(infd_), infd_ = -1; close(outfd_), outfd_ = -1; bfree(&graphic_[0].b); bfree(&graphic_[1].b); bfree(&vtframe_[0].b); bfree(&vtframe_[1].b); bfree(&xtcodes_); bfree(&audio_); CloseSpeaker(); } static void MakeLatencyLittleLessBad(void) { #ifdef __x86_64__ _peekall(); #endif LOGIFNEG1(sys_mlockall(MCL_CURRENT)); LOGIFNEG1(nice(-5)); } static void PickDefaults(void) { /* * Direct color ain't true color -- it just means xterm does the * xterm256 rgb quantization for you. we're better at xterm256 * than xterm is, so we don't need the training wheels. * * strcmp(nulltoempty(getenv("TERM")), "xterm-direct") == 0 */ if (strcmp(nulltoempty(getenv("TERM")), "xterm-kitty") == 0) { ttyquantsetup(kTtyQuantTrue, TTYQUANT()->chans, kTtyBlocksUnicode); } } static void RenounceSpecialPrivileges(void) { if (issetugid()) { setegid(getgid()); seteuid(getuid()); } } #define FBIOGET_VSCREENINFO 0x4600 #define FBIOGET_FSCREENINFO 0x4602 static void TryToOpenFrameBuffer(void) { /* * Linux (i.e. without some X or Wayland thing running on top of it) * is barely able to display any non-ascii characters, so things look * much better if we can access the framebuffer. */ int rc; fb0_.fd = -1; fb0_.path = NULL; if (!isempty(getenv("FRAMEBUFFER"))) { fb0_.path = strdup(getenv("FRAMEBUFFER")); } else if (strcmp(nulltoempty(getenv("TERM")), "linux") == 0) { fb0_.path = strdup("/dev/fb0"); } if ((fb0_.fd = open(fb0_.path, O_RDWR)) != -1) { CHECK_NE(-1, (rc = ioctl(fb0_.fd, FBIOGET_FSCREENINFO, &fb0_.fscreen))); INFOF("ioctl(%s) → %d", "FBIOGET_FSCREENINFO", rc); INFOF("%s.%s=%.*s", "fb0_.fscreen", "id", sizeof(fb0_.fscreen.id), fb0_.fscreen.id); INFOF("%s.%s=%p", "fb0_.fscreen", "smem_start", fb0_.fscreen.smem_start); INFOF("%s.%s=%u", "fb0_.fscreen", "smem_len", fb0_.fscreen.smem_len); INFOF("%s.%s=%u", "fb0_.fscreen", "type", fb0_.fscreen.type); INFOF("%s.%s=%u", "fb0_.fscreen", "type_aux", fb0_.fscreen.type_aux); INFOF("%s.%s=%u", "fb0_.fscreen", "visual", fb0_.fscreen.visual); INFOF("%s.%s=%hu", "fb0_.fscreen", "xpanstep", fb0_.fscreen.xpanstep); INFOF("%s.%s=%hu", "fb0_.fscreen", "ypanstep", fb0_.fscreen.ypanstep); INFOF("%s.%s=%hu", "fb0_.fscreen", "ywrapstep", fb0_.fscreen.ywrapstep); INFOF("%s.%s=%u", "fb0_.fscreen", "line_length", fb0_.fscreen.line_length); INFOF("%s.%s=%p", "fb0_.fscreen", "mmio_start", fb0_.fscreen.mmio_start); INFOF("%s.%s=%u", "fb0_.fscreen", "mmio_len", fb0_.fscreen.mmio_len); INFOF("%s.%s=%u", "fb0_.fscreen", "accel", fb0_.fscreen.accel); INFOF("%s.%s=%#b", "fb0_.fscreen", "capabilities", fb0_.fscreen.capabilities); CHECK_NE(-1, (rc = ioctl(fb0_.fd, FBIOGET_VSCREENINFO, &fb0_.vscreen))); INFOF("ioctl(%s) → %d", "FBIOGET_VSCREENINFO", rc); INFOF("%s.%s=%u", "fb0_.vscreen", "xres", fb0_.vscreen.xres); INFOF("%s.%s=%u", "fb0_.vscreen", "yres", fb0_.vscreen.yres); INFOF("%s.%s=%u", "fb0_.vscreen", "xres_virtual", fb0_.vscreen.xres_virtual); INFOF("%s.%s=%u", "fb0_.vscreen", "yres_virtual", fb0_.vscreen.yres_virtual); INFOF("%s.%s=%u", "fb0_.vscreen", "xoffset", fb0_.vscreen.xoffset); INFOF("%s.%s=%u", "fb0_.vscreen", "yoffset", fb0_.vscreen.yoffset); INFOF("%s.%s=%u", "fb0_.vscreen", "bits_per_pixel", fb0_.vscreen.bits_per_pixel); INFOF("%s.%s=%u", "fb0_.vscreen", "grayscale", fb0_.vscreen.grayscale); INFOF("%s.%s=%u", "fb0_.vscreen.red", "offset", fb0_.vscreen.red.offset); INFOF("%s.%s=%u", "fb0_.vscreen.red", "length", fb0_.vscreen.red.length); INFOF("%s.%s=%u", "fb0_.vscreen.red", "msb_right", fb0_.vscreen.red.msb_right); INFOF("%s.%s=%u", "fb0_.vscreen.green", "offset", fb0_.vscreen.green.offset); INFOF("%s.%s=%u", "fb0_.vscreen.green", "length", fb0_.vscreen.green.length); INFOF("%s.%s=%u", "fb0_.vscreen.green", "msb_right", fb0_.vscreen.green.msb_right); INFOF("%s.%s=%u", "fb0_.vscreen.blue", "offset", fb0_.vscreen.blue.offset); INFOF("%s.%s=%u", "fb0_.vscreen.blue", "length", fb0_.vscreen.blue.length); INFOF("%s.%s=%u", "fb0_.vscreen.blue", "msb_right", fb0_.vscreen.blue.msb_right); INFOF("%s.%s=%u", "fb0_.vscreen.transp", "offset", fb0_.vscreen.transp.offset); INFOF("%s.%s=%u", "fb0_.vscreen.transp", "length", fb0_.vscreen.transp.length); INFOF("%s.%s=%u", "fb0_.vscreen.transp", "msb_right", fb0_.vscreen.transp.msb_right); INFOF("%s.%s=%u", "fb0_.vscreen", "nonstd", fb0_.vscreen.nonstd); INFOF("%s.%s=%u", "fb0_.vscreen", "activate", fb0_.vscreen.activate); INFOF("%s.%s=%u", "fb0_.vscreen", "height", fb0_.vscreen.height); INFOF("%s.%s=%u", "fb0_.vscreen", "width", fb0_.vscreen.width); INFOF("%s.%s=%u", "fb0_.vscreen", "accel_flags", fb0_.vscreen.accel_flags); INFOF("%s.%s=%u", "fb0_.vscreen", "pixclock", fb0_.vscreen.pixclock); INFOF("%s.%s=%u", "fb0_.vscreen", "left_margin", fb0_.vscreen.left_margin); INFOF("%s.%s=%u", "fb0_.vscreen", "right_margin", fb0_.vscreen.right_margin); INFOF("%s.%s=%u", "fb0_.vscreen", "upper_margin", fb0_.vscreen.upper_margin); INFOF("%s.%s=%u", "fb0_.vscreen", "lower_margin", fb0_.vscreen.lower_margin); INFOF("%s.%s=%u", "fb0_.vscreen", "hsync_len", fb0_.vscreen.hsync_len); INFOF("%s.%s=%u", "fb0_.vscreen", "vsync_len", fb0_.vscreen.vsync_len); INFOF("%s.%s=%u", "fb0_.vscreen", "sync", fb0_.vscreen.sync); INFOF("%s.%s=%u", "fb0_.vscreen", "vmode", fb0_.vscreen.vmode); INFOF("%s.%s=%u", "fb0_.vscreen", "rotate", fb0_.vscreen.rotate); INFOF("%s.%s=%u", "fb0_.vscreen", "colorspace", fb0_.vscreen.colorspace); fb0_.size = fb0_.fscreen.smem_len; CHECK_NE(MAP_FAILED, (fb0_.map = mmap(NULL, fb0_.size, PROT_READ | PROT_WRITE, MAP_SHARED, fb0_.fd, 0))); } } int main(int argc, char *argv[]) { sigset_t wut; gamma_ = 2.4; volscale_ -= 2; dither_ = true; sigemptyset(&wut); sigaddset(&wut, SIGCHLD); sigaddset(&wut, SIGPIPE); sigprocmask(SIG_SETMASK, &wut, NULL); ShowCrashReports(); fullclear_ = true; GetOpts(argc, argv); if (!tuned_) PickDefaults(); if (optind == argc) PrintUsage(EX_USAGE, stderr); patharg_ = argv[optind]; sox_ = strdup(commandvenv("SOX", "sox")); ffplay_ = strdup(commandvenv("FFPLAY", "ffplay")); infd_ = STDIN_FILENO; outfd_ = STDOUT_FILENO; if (!setjmp(jb_)) { xsigaction(SIGINT, OnCtrlC, 0, 0, NULL); xsigaction(SIGHUP, OnCtrlC, 0, 0, NULL); xsigaction(SIGTERM, OnCtrlC, 0, 0, NULL); xsigaction(SIGWINCH, OnResize, 0, 0, NULL); xsigaction(SIGCHLD, OnSigChld, 0, 0, NULL); xsigaction(SIGPIPE, OnSigPipe, 0, 0, NULL); if (ttyraw(kTtyLfToCrLf) != -1) ttymode_ = true; __cxa_atexit(OnExit, NULL, NULL); __log_file = fopen(logpath_, "a"); if (ischardev(infd_) && ischardev(outfd_)) { /* CHECK_NE(-1, fcntl(infd_, F_SETFL, O_NONBLOCK)); */ } else if (infd_ != outfd_) { infd_ = -1; } /* CHECK_NE(-1, fcntl(outfd_, F_SETFL, O_NONBLOCK)); */ if (CanPlayAudio()) MakeLatencyLittleLessBad(); TryToOpenFrameBuffer(); RenounceSpecialPrivileges(); if (t2 > t1) longjmp(jb_, 1); OpenVideo(); DimensionDisplay(); starttime_ = nowl(); PrintVideo(); } INFOF("jb_ triggered"); return 0; }
50,266
1,581
jart/cosmopolitan
false
cosmopolitan/tool/viz/getopts.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/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview Tool for printing which getopt() letters are used, e.g. * * o//tool/viz/getopts.com jkazhdugvVsmbBfe:A:l:p:r:R:H */ int letters_used[256]; bool letters_with_args[256]; bool IsLegal(int c) { return isgraph(c) && c != ':' && c != '?'; } int main(int argc, char *argv[]) { int i, j; bool hasargless; for (i = 1; i < argc; ++i) { for (j = 0; argv[i][j]; ++j) { ++letters_used[argv[i][j] & 255]; if (argv[i][j + 1] == ':') { letters_with_args[argv[i][j] & 255] = true; } } } // usage report fprintf(stderr, "// options used: "); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i]) { if (j++) fprintf(stderr, ""); fprintf(stderr, "%c", i); } } if (!j) fprintf(stderr, "none"); fprintf(stderr, "\n"); fprintf(stderr, "// letters not used: "); for (j = i = 0; i < 128; ++i) { if (!isalpha(i)) continue; if (!letters_used[i]) { if (j++) fprintf(stderr, ""); fprintf(stderr, "%c", i); } } if (!j) fprintf(stderr, "none"); fprintf(stderr, "\n"); fprintf(stderr, "// digits not used: "); for (j = i = 0; i < 128; ++i) { if (!isdigit(i)) continue; if (!letters_used[i]) { if (j++) fprintf(stderr, ""); fprintf(stderr, "%c", i); } } if (!j) fprintf(stderr, "none"); fprintf(stderr, "\n"); fprintf(stderr, "// puncts not used: "); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (isalnum(i)) continue; if (!letters_used[i]) { if (j++) fprintf(stderr, ""); fprintf(stderr, "%c", i); } } if (!j) fprintf(stderr, "none"); fprintf(stderr, "\n"); fprintf(stderr, "// letters duplicated: "); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i] > 1) { if (j++) fprintf(stderr, ""); fprintf(stderr, "%c", i); } } if (!j) fprintf(stderr, "none"); fprintf(stderr, "\n"); // generated code hasargless = false; printf("#define GETOPTS \""); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i] && !letters_with_args[i]) { printf("%c", i); hasargless = true; } } for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i] && letters_with_args[i]) { printf("%c:", i); } } printf("\"\n"); printf("\n#define USAGE \"\\\n"); printf("Usage: program.com"); if (hasargless) { printf(" [-"); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i] && !letters_with_args[i]) { printf("%c", i); hasargless = true; } } printf("]"); } printf(" ARGS...\\n\\\n"); for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i] && !letters_with_args[i]) { printf(" -%c the %c option\\n\\\n", i, i); } } for (j = i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_with_args[i]) { printf(" -%c VAL the %c option\\n\\\n", i, i); } } printf("\"\n\n"); for (i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i]) { if (letters_with_args[i]) { printf("const char *"); } else { printf("int "); } if (isalnum(i) || i == '_') { printf("g_%cflag;\n", i); } } } printf("\n\ static void GetOpts(int argc, char *argv[]) {\n\ int opt;\n\ while ((opt = getopt(argc, argv, GETOPTS)) != -1) {\n\ switch (opt) {\n"); for (i = 0; i < 128; ++i) { if (!IsLegal(i)) continue; if (letters_used[i]) { printf(" case '%c':\n", i); if (isalnum(i) || i == '_') { printf(" g_%cflag", i); } else { printf(" g_XXXflag", i); } if (letters_with_args[i]) { printf(" = optarg;\n"); } else { printf("++;\n"); } printf(" break;\n"); } } printf(" case '?':\n"); printf(" write(1, USAGE, sizeof(USAGE) - 1);\n"); printf(" exit(0);\n"); printf(" default:\n"); printf(" write(2, USAGE, sizeof(USAGE) - 1);\n"); printf(" exit(64);\n"); printf(" }\n"); printf(" }\n"); printf("}\n"); printf("\n"); printf("int main(int argc, char *argv[]) {\n"); printf(" GetOpts(argc, argv);\n"); printf("}\n"); return 0; }
6,308
200
jart/cosmopolitan
false
cosmopolitan/tool/viz/tailf.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/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/intrin/safemacros.internal.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" #include "libc/x/xsigaction.h" /** * @fileoverview tail -f with lower poll rate * @see busybox not having interval flag */ int fd; bool exited; struct stat st; char buf[FRAMESIZE]; int WriteString(const char *s) { return write(1, s, strlen(s)); } void HideCursor(void) { WriteString("\e[?25l"); } void ShowCursor(void) { WriteString("\e[?25h"); } void OnInt(void) { exited = true; } void OnExit(void) { ShowCursor(); } int main(int argc, char *argv[]) { char *p; ssize_t n; size_t i, j; bool chopped; if (argc < 2) return 1; if ((fd = open(argv[1], O_RDONLY)) == -1) return 2; if (fstat(fd, &st) == -1) return 3; n = st.st_size - MIN(st.st_size, sizeof(buf)); if ((n = pread(fd, buf, sizeof(buf), n)) == -1) return 4; for (p = buf + n, i = 0; i < 10; ++i) { p = firstnonnull(memrchr(buf, '\n', p - buf), buf); } chopped = false; if (buf + n - p) ++p; i = st.st_size - (buf + n - p); atexit(OnExit); HideCursor(); xsigaction(SIGINT, OnInt, 0, 0, 0); xsigaction(SIGTERM, OnInt, 0, 0, 0); while (!exited) { if (fstat(fd, &st) == -1) return 5; if (i > st.st_size) i = 0; for (; i < st.st_size; i += n) { if ((n = pread(fd, buf, sizeof(buf), i)) == -1) return 6; j = n; while (j && (buf[j - 1] == '\n' || buf[j - 1] == '\r')) --j; if (j) { if (chopped) { WriteString("\r\n"); } write(1, buf, j); } chopped = j != n; } dsleep(.01); } close(fd); WriteString("\r\n"); return 0; }
3,698
102
jart/cosmopolitan
false
cosmopolitan/tool/viz/memzoom.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 "dsp/scale/cdecimate2xuint8x8.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/calls/ucontext.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/intrin/bsf.h" #include "libc/intrin/hilbert.h" #include "libc/intrin/morton.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/tpenc.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/sock/sock.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/str/unicode.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/termios.h" #include "libc/time/time.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [-hznmHNW] [-p PID] [PATH]\n\ \n\ DESCRIPTION\n\ \n\ Memory Viewer\n\ \n\ FLAGS\n\ \n\ -h help\n\ -z zoom\n\ -m morton ordering\n\ -H hilbert ordering\n\ -N natural scrolling\n\ -W white terminal background\n\ -p PID shows process virtual memory\n\ -f INT frames per second [default 10]\n\ \n\ SHORTCUTS\n\ \n\ z or + zoom\n\ Z or - unzoom\n\ ctrl+wheel zoom point\n\ wheel scroll\n\ l linearize\n\ m mortonize\n\ h hilbertify\n\ n next mapping\n\ N next mapping ending\n\ p prev mapping\n\ P prev mapping ending\n\ k up\n\ j down\n\ b page up\n\ space page down\n\ g home\n\ G end\n\ q quit\n\ \n" #define CTRL(C) ((C) ^ 0100) #define MAXZOOM 14 #define COLOR 253 #define LINEAR 0 #define MORTON 1 #define HILBERT 2 #define INTERRUPTED 0x1 #define RESIZED 0x2 #define MOUSE_LEFT_DOWN 0 #define MOUSE_MIDDLE_DOWN 1 #define MOUSE_RIGHT_DOWN 2 #define MOUSE_LEFT_UP 4 #define MOUSE_MIDDLE_UP 5 #define MOUSE_RIGHT_UP 6 #define MOUSE_LEFT_DRAG 32 #define MOUSE_MIDDLE_DRAG 33 #define MOUSE_RIGHT_DRAG 34 #define MOUSE_WHEEL_UP 64 #define MOUSE_WHEEL_DOWN 65 #define MOUSE_CTRL_WHEEL_UP 80 #define MOUSE_CTRL_WHEEL_DOWN 81 struct Ranges { long i; struct Range { long a; long b; } p[512]; }; static const signed char kThePerfectKernel[8] = {-1, -3, 3, 17, 17, 3, -3, -1}; static bool white; static bool natural; static bool mousemode; static int fd; static int pid; static int out; static int fps; static int zoom; static int order; static int action; static long tyn; static long txn; static long size; static long offset; static long lowest; static long highest; static long canvassize; static long buffersize; static long displaysize; static char *buffer; static uint8_t *canvas; static struct stat st; static struct Ranges ranges; static struct termios oldterm; static char path[PATH_MAX]; static char mapspath[PATH_MAX]; static int Write(const char *s) { return write(out, s, strlen(s)); } static void HideCursor(void) { Write("\e[?25l"); } static void ShowCursor(void) { Write("\e[?25h"); } static void EnableMouse(void) { mousemode = true; Write("\e[?1000;1002;1015;1006h"); } static void DisableMouse(void) { mousemode = false; Write("\e[?1000;1002;1015;1006l"); } static void LeaveScreen(void) { Write("\e[H\e[J"); } static void GetTtySize(void) { struct winsize wsize; wsize.ws_row = tyn + 1; wsize.ws_col = txn; _getttysize(out, &wsize); tyn = MAX(2, wsize.ws_row) - 1; txn = MAX(17, wsize.ws_col) - 16; tyn = _rounddown2pow(tyn); txn = _rounddown2pow(txn); tyn = MIN(tyn, txn); } static void EnableRaw(void) { struct termios term; memcpy(&term, &oldterm, sizeof(term)); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 1; term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON); term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL); term.c_cflag &= ~(CSIZE | PARENB); term.c_cflag |= CS8; term.c_iflag |= IUTF8; ioctl(out, TCSETS, &term); } static void OnExit(void) { LeaveScreen(); ShowCursor(); DisableMouse(); ioctl(out, TCSETS, &oldterm); } static void OnSigInt(int sig, struct siginfo *sa, void *uc) { action |= INTERRUPTED; } static void OnSigWinch(int sig, struct siginfo *sa, void *uc) { action |= RESIZED; } static void Setup(void) { tyn = 80; txn = 24; action = RESIZED; ioctl(out, TCGETS, &oldterm); HideCursor(); EnableRaw(); EnableMouse(); atexit(OnExit); sigaction(SIGINT, &(struct sigaction){.sa_sigaction = OnSigInt}, NULL); sigaction(SIGWINCH, &(struct sigaction){.sa_sigaction = OnSigWinch}, NULL); } static wontreturn void FailPath(const char *s, int rc) { Write("error: "); Write(s); Write(": "); Write(path); Write("\n"); exit(rc); } static void SetExtent(long lo, long hi) { lowest = lo; highest = hi; offset = MIN(hi, MAX(lo, offset)); } static void Open(void) { int err; if ((fd = open(path, O_RDONLY)) == -1) { FailPath("open() failed", errno); } fstat(fd, &st); size = st.st_size; SetExtent(0, size); } static void *Allocate(size_t n) { return mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); } static void SetupCanvas(void) { if (canvassize) { munmap(canvas, canvassize); munmap(buffer, buffersize); } displaysize = ROUNDUP(ROUNDUP((tyn * txn) << zoom, 16), 1ul << zoom); canvassize = ROUNDUP(displaysize, FRAMESIZE); buffersize = ROUNDUP(tyn * txn * 16 + PAGESIZE, FRAMESIZE); canvas = Allocate(canvassize); buffer = Allocate(buffersize); } static long IndexSquare(long y, long x) { switch (order) { case LINEAR: return y * txn + x; case MORTON: return morton(y, x); case HILBERT: return hilbert(txn, y, x); default: return 0; } } static long Index(long y, long x) { long i; if (order == LINEAR) { i = 0; } else { i = x / tyn; x = x % tyn; } return i * tyn * tyn + IndexSquare(y, x); } static void PreventBufferbloat(void) { long double now, rate; static long double last; now = nowl(); rate = 1. / fps; if (now - last < rate) { dsleep(rate - (now - last)); } last = now; } static bool HasPendingInput(void) { struct pollfd fds[1]; if (IsWindows()) return true; /* XXX */ fds[0].fd = 0; fds[0].events = POLLIN; fds[0].revents = 0; poll(fds, ARRAYLEN(fds), 0); return fds[0].revents & (POLLIN | POLLERR); } static int GetCurrentRange(void) { int i; if (ranges.i) { for (i = 0; i < ranges.i; ++i) { if (offset < ranges.p[i].a) return MAX(0, i - 1); if (offset < ranges.p[i].b) return i; } return ranges.i - 1; } else { return -1; } } static void Move(long d) { d <<= zoom; offset = MIN(highest, MAX(lowest, (offset + d) >> zoom << zoom)); } static void SetZoom(long y, long x, int d) { long a, b, i; if ((0 <= y && y < tyn) && (0 <= x && x < txn)) { i = Index(y, x); a = zoom; b = MIN(MAXZOOM, MAX(0, a + d)); zoom = b; Move((i << a) - (i << b)); SetupCanvas(); } } static void OnZoom(long y, long x) { SetZoom(y, x, +1); } static void OnUnzoom(long y, long x) { SetZoom(y, x, -1); } static void OnUp(void) { Move(-(txn)); } static void OnDown(void) { Move(txn); } static void OnPageUp(void) { Move(-(txn * (tyn - 2))); } static void OnPageDown(void) { Move(txn * (tyn - 2)); } static void OnHome(void) { offset = lowest; } static void OnEnd(void) { offset = MAX(lowest, highest - txn * tyn); } static void OnLinear(void) { order = LINEAR; GetTtySize(); SetupCanvas(); } static void OnMorton(void) { order = MORTON; SetupCanvas(); } static void OnHilbert(void) { order = HILBERT; SetupCanvas(); } static void OnNext(void) { int i; if ((i = GetCurrentRange()) != -1) { if (i + 1 < ranges.i) { offset = ranges.p[i + 1].a; } } } static void OnPrev(void) { int i; if ((i = GetCurrentRange()) != -1) { if (i) { offset = ranges.p[i - 1].a; } } } static void OnNextEnd(void) { long i, n; if ((i = GetCurrentRange()) != -1) { n = (tyn * txn) << zoom; if (offset < ranges.p[i].b - n) { offset = ranges.p[i].b - n; } else if (i + 1 < ranges.i) { offset = MAX(ranges.p[i + 1].a, ranges.p[i + 1].b - n); } } } static void OnPrevEnd(void) { long i, n; if ((i = GetCurrentRange()) != -1) { n = (tyn * txn) << zoom; if (i) { offset = MAX(ranges.p[i - 1].a, ranges.p[i - 1].b - n); } } } static void OnMouse(char *p) { int e, x, y; e = strtol(p, &p, 10); if (*p == ';') ++p; x = min(txn, max(1, strtol(p, &p, 10))) - 1; if (*p == ';') ++p; y = min(tyn, max(1, strtol(p, &p, 10))) - 1; e |= (*p == 'm') << 2; switch (e) { case MOUSE_WHEEL_UP: if (natural) { OnDown(); OnDown(); OnDown(); } else { OnUp(); OnUp(); OnUp(); } break; case MOUSE_WHEEL_DOWN: if (natural) { OnUp(); OnUp(); OnUp(); } else { OnDown(); OnDown(); OnDown(); } break; case MOUSE_CTRL_WHEEL_UP: if (natural) { OnZoom(y, x); } else { OnUnzoom(y, x); } break; case MOUSE_CTRL_WHEEL_DOWN: if (natural) { OnUnzoom(y, x); } else { OnZoom(y, x); } break; default: break; } } static void ReadKeyboard(void) { char buf[32], *p = buf; bzero(buf, sizeof(buf)); if (readansi(0, buf, sizeof(buf)) == -1) { if (errno == EINTR) return; exit(errno); } switch (*p++) { case 'q': exit(0); case '+': case 'z': OnZoom(0, 0); break; case '-': case 'Z': OnUnzoom(0, 0); break; case 'b': OnPageUp(); break; case 'n': OnNext(); break; case 'p': OnPrev(); break; case 'N': OnNextEnd(); break; case 'P': OnPrevEnd(); break; case ' ': case CTRL('V'): OnPageDown(); break; case 'g': OnHome(); break; case 'G': OnEnd(); break; case 'k': case CTRL('P'): OnUp(); break; case 'j': case CTRL('N'): OnDown(); break; case 'l': OnLinear(); break; case 'm': if (order == MORTON) { OnLinear(); } else { OnMorton(); } break; case 'M': if (mousemode) { DisableMouse(); } else { EnableMouse(); } break; case 'h': case 'H': if (order == HILBERT) { OnLinear(); } else { OnHilbert(); } break; case '\e': switch (*p++) { case 'v': OnPageUp(); break; case '[': switch (*p++) { case '<': OnMouse(p); break; case 'A': OnUp(); break; case 'B': OnDown(); break; case 'F': OnEnd(); break; case 'H': OnHome(); break; case '1': switch (*p++) { case '~': OnHome(); break; default: break; } break; case '4': switch (*p++) { case '~': OnEnd(); break; default: break; } break; case '5': switch (*p++) { case '~': OnPageUp(); break; default: break; } break; case '6': switch (*p++) { case '~': OnPageDown(); break; default: break; } break; case '7': switch (*p++) { case '~': OnHome(); break; default: break; } break; case '8': switch (*p++) { case '~': OnEnd(); break; default: break; } break; default: break; } break; default: break; } break; default: break; } } static void LoadRanges(void) { char b[512]; struct Range range; int i, t, n, fd, err; if ((fd = open(mapspath, O_RDONLY)) == -1) { err = errno; Write("error: process died\n"); exit(err); } t = 0; range.a = 0; range.b = 0; ranges.i = 0; for (;;) { if ((n = read(fd, b, sizeof(b))) == -1) exit(1); if (!n) break; for (i = 0; i < n; ++i) { switch (t) { case 0: if (isxdigit(b[i])) { range.a <<= 4; range.a += hextoint(b[i]); } else if (b[i] == '-') { t = 1; } break; case 1: if (isxdigit(b[i])) { range.b <<= 4; range.b += hextoint(b[i]); } else if (b[i] == ' ') { t = 2; } break; case 2: if (b[i] == '\n') { if (ranges.i < ARRAYLEN(ranges.p)) { ranges.p[ranges.i++] = range; } range.a = 0; range.b = 0; t = 0; } break; default: unreachable; } } } close(fd); if (ranges.i) { SetExtent(ranges.p[0].a, ranges.p[ranges.i - 1].b); } else { SetExtent(0, 0); } } static int InvertXtermGreyscale(int x) { return -(x - 232) + 255; } static void Render(void) { char *p; int c, fg2, rc, fg; long i, y, x, w, n, got; p = buffer; p = stpcpy(p, "\e[H"); for (y = 0; y < tyn; ++y) { fg = -1; for (x = 0; x < txn; ++x) { c = canvas[Index(y, x)]; if (c < 32) { fg2 = 237 + c * ((COLOR - 237) / 32.); } else if (c >= 232) { fg2 = COLOR + (c - 232) * ((255 - COLOR) / (256. - 232)); } else { fg2 = COLOR; } if (fg2 != fg) { fg = fg2; if (white) { fg = InvertXtermGreyscale(fg); } p = stpcpy(p, "\e[38;5;"); p = FormatInt64(p, fg); *p++ = 'm'; } w = _tpenc(kCp437[c]); do { *p++ = w & 0xff; w >>= 8; } while (w); } p = stpcpy(p, "\e[0m "); p += uint64toarray_radix16(offset + ((y * txn) << zoom), p); p = stpcpy(p, "\e[K\r\n"); } p = stpcpy(p, "\e[7m\e[K"); n = strlen(path); if (n > txn - 3 - 1 - 7) { p = mempcpy(p, path, txn - 1 - 7 - 3); p = stpcpy(p, "..."); } else { p = stpcpy(p, path); for (i = n; i < txn - 1 - 7; ++i) { *p++ = ' '; } } p = stpcpy(p, " memzoom\e[0m "); if (!pid) { p = FormatUint32(p, MIN(offset / (long double)size * 100, 100)); p = stpcpy(p, "%-"); p = FormatUint32( p, MIN((offset + ((tyn * txn) << zoom)) / (long double)size * 100, 100)); p = stpcpy(p, "% "); } p = FormatUint32(p, 1L << zoom); p = stpcpy(p, "x\e[J"); PreventBufferbloat(); for (i = 0, n = p - buffer; i < n; i += got) { got = 0; if ((rc = write(out, buffer + i, n - i)) == -1) { if (errno == EINTR) continue; exit(errno); } got = rc; } } static void Zoom(long have) { long i, n, r; n = canvassize; for (i = 0; i < zoom; ++i) { cDecimate2xUint8x8(n, canvas, kThePerfectKernel); n >>= 1; } if (n < tyn * txn) { bzero(canvas + n, canvassize - n); } if (have != -1) { n = have >> zoom; i = n / txn; r = n % txn; if (r) ++i; if (order == LINEAR) { for (; i < tyn; ++i) { canvas[txn * i] = '~'; } } } } static void FileZoom(void) { long have; have = MIN(displaysize, size - offset); have = pread(fd, canvas, have, offset); have = MAX(0, have); bzero(canvas + have, canvassize - have); Zoom(have); Render(); } static void RangesZoom(void) { long a, b, c, d, i; LoadRanges(); memset(canvas, 1, canvassize); a = offset; b = MIN(highest, offset + ((tyn * txn) << zoom)); for (i = 0; i < ranges.i; ++i) { if ((a >= ranges.p[i].a && a < ranges.p[i].b) || (b >= ranges.p[i].a && b < ranges.p[i].b) || (a < ranges.p[i].a && b >= ranges.p[i].b)) { c = MAX(a, ranges.p[i].a); d = MIN(b, ranges.p[i].b); pread(fd, canvas + (c - offset), d - c, c); } } Zoom(-1); Render(); } static void MemZoom(void) { bool ok; ok = false; do { if (action & RESIZED) { GetTtySize(); SetupCanvas(); action &= ~RESIZED; } if (ok && HasPendingInput()) { ReadKeyboard(); if (!IsWindows()) continue; /* XXX */ } ok = true; if (pid) { RangesZoom(); } else { FileZoom(); } } while (!(action & INTERRUPTED)); } static wontreturn void PrintUsage(int rc) { Write("SYNOPSIS\n\n "); Write(program_invocation_name); Write(USAGE); exit(rc); } static void GetOpts(int argc, char *argv[]) { int opt; char *p; fps = 10; while ((opt = getopt(argc, argv, "hzHNWf:p:")) != -1) { switch (opt) { case 'z': ++zoom; break; case 'm': order = MORTON; break; case 'H': order = HILBERT; break; case 'W': white = true; break; case 'N': natural = true; break; case 'f': fps = strtol(optarg, NULL, 0); fps = MAX(1, fps); break; case 'p': if (strcmp(optarg, "self") == 0) { pid = getpid(); } else { pid = strtol(optarg, NULL, 0); } break; case 'h': PrintUsage(EXIT_SUCCESS); default: PrintUsage(EX_USAGE); } } if (pid) { p = stpcpy(path, "/proc/"); p = FormatInt64(p, pid); stpcpy(p, "/mem"); p = stpcpy(mapspath, "/proc/"); p = FormatInt64(p, pid); stpcpy(p, "/maps"); } else { if (optind == argc) { PrintUsage(EX_USAGE); } if (!memccpy(path, argv[optind], '\0', sizeof(path))) { PrintUsage(EX_USAGE); } } } int main(int argc, char *argv[]) { if (!NoDebug()) ShowCrashReports(); out = 1; GetOpts(argc, argv); Open(); Setup(); MemZoom(); return 0; }
21,008
939
jart/cosmopolitan
false
cosmopolitan/tool/viz/generatematrix.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/fmt/fmt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/lcg.internal.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" #include "third_party/getopt/getopt.h" #include "tool/viz/lib/formatstringtable.h" typedef double (*round_f)(double); typedef unsigned long (*rand_f)(void); struct Range { long double a; long double b; }; short xn_ = 8; short yn_ = 8; double digs_ = 6; rand_f rand_; round_f rounder_; const char *path_ = "-"; const char *name_ = "M"; const char *type_ = "float"; struct Range r1_ = {LONG_MIN, LONG_MAX}; struct Range r2_ = {0, 1}; StringTableFormatter *formatter_ = FormatStringTableAsCode; static wontreturn void PrintUsage(int rc, FILE *f) { fprintf(f, "Usage: %s%s", program_invocation_name, "\ [FLAGS] [FILE]\n\ \n\ Flags:\n\ -u unsigned\n\ -c char\n\ -s short\n\ -i int\n\ -l long\n\ -d double\n\ -b bytes [-uc]\n\ -g non-deterministic rng\n\ -S output assembly\n\ -W output whitespace\n\ -o PATH output path\n\ -x FLEX\n\ -w FLEX width\n\ -y FLEX\n\ -h FLEX height\n\ -N NAME name\n\ -T NAME type name\n\ -A FLEX min value\n\ -B FLEX max value\n\ -R FUNC round function for indexing\n\ -D FLEX decimal digits to printout\n\ -v increases verbosity\n\ -? shows this information\n\ \n"); exit(rc); } static bool StringEquals(const char *a, const char *b) { return strcasecmp(a, b) == 0; } static wontreturn void ShowInvalidArg(const char *name, const char *s, const char *type) { fprintf(stderr, "error: invalid %s %s: %s\n", type, name, s); exit(EXIT_FAILURE); } static double ParseFlexidecimalOrDie(const char *name, const char *s, double min, double max) { double x; s = firstnonnull(s, "NULL"); if (strchr(s, '.') || strchr(s, 'e')) { x = strtod(s, NULL); } else { x = strtol(s, NULL, 0); } if (min <= x && x <= max) { return x; } else { ShowInvalidArg(name, s, "flexidecimal"); } } static round_f ParseRoundingFunctionOrDie(const char *s) { if (isempty(s) || StringEquals(s, "none") || StringEquals(s, "null")) { return NULL; } else if (StringEquals(s, "round")) { return round; } else if (StringEquals(s, "rint")) { return rint; } else if (StringEquals(s, "nearbyint")) { return nearbyint; } else if (StringEquals(s, "trunc")) { return trunc; } else if (StringEquals(s, "floor")) { return floor; } else if (StringEquals(s, "ceil")) { return ceil; } else { ShowInvalidArg("round", s, "func"); } } static void ConfigureIntegralRange(const char *type, long min, long max) { type_ = type; r1_.a = min; r1_.b = max; r2_.a = min; r2_.b = max; if (!rounder_) rounder_ = round; } void GetOpts(int argc, char *argv[]) { int opt; bool want_unsigned, want_char, want_short, want_int, want_long, want_double; want_unsigned = false; want_char = false; want_short = false; want_int = false; want_long = false; want_double = false; if (argc == 2 && (StringEquals(argv[1], "--help") || StringEquals(argv[1], "-help"))) { PrintUsage(EXIT_SUCCESS, stdout); } while ((opt = getopt(argc, argv, "?vubcsildgSWo:x:w:y:h:N:A:B:C:E:T:R:D:")) != -1) { switch (opt) { case 'b': want_unsigned = true; want_char = true; break; case 'u': want_unsigned = true; break; case 'c': want_char = true; break; case 's': want_short = true; break; case 'i': want_int = true; break; case 'l': want_long = true; break; case 'd': want_double = true; break; case 'g': rand_ = _rand64; break; case 'N': name_ = optarg; break; case 'o': path_ = optarg; break; case 'S': formatter_ = FormatStringTableAsAssembly; break; case 'W': formatter_ = FormatStringTableBasic; break; case 't': type_ = optarg; break; case 'x': case 'w': xn_ = ParseFlexidecimalOrDie("width", optarg, 1, SHRT_MAX); break; case 'y': case 'h': yn_ = ParseFlexidecimalOrDie("height", optarg, 1, SHRT_MAX); break; case 'D': digs_ = ParseFlexidecimalOrDie("digs", optarg, 0, 15.95); break; case 'r': rounder_ = ParseRoundingFunctionOrDie(optarg); break; case 'A': r1_.a = ParseFlexidecimalOrDie("r1_.a", optarg, INT_MIN, INT_MAX); break; case 'B': r1_.b = ParseFlexidecimalOrDie("r1_.b", optarg, INT_MIN, INT_MAX); break; case 'C': r2_.a = ParseFlexidecimalOrDie("r2_.a", optarg, INT_MIN, INT_MAX); break; case 'E': r2_.b = ParseFlexidecimalOrDie("r2_.b", optarg, INT_MIN, INT_MAX); break; case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } if (want_unsigned && want_char) { ConfigureIntegralRange("unsigned char", 0, 255); } else if (want_char) { ConfigureIntegralRange("signed char", -128, 127); } else if (want_unsigned && want_short) { ConfigureIntegralRange("unsigned short", USHRT_MIN, USHRT_MAX); } else if (want_short) { ConfigureIntegralRange("short", SHRT_MIN, SHRT_MAX); } else if (want_unsigned && want_int) { ConfigureIntegralRange("unsigned", UINT_MIN, UINT_MAX); } else if (want_int) { ConfigureIntegralRange("int", INT_MIN, INT_MAX); } else if (want_unsigned && want_long) { ConfigureIntegralRange("unsigned long", ULONG_MIN, ULONG_MAX); } else if (want_long) { ConfigureIntegralRange("long", LONG_MIN, LONG_MAX); } else if (want_double) { type_ = "double"; r1_.a = LONG_MIN; r1_.b = LONG_MAX; digs_ = 19; } } static void *SetRandom(long n, long p[n]) { long i; uint64_t r; if (rand_) { for (r = 1, i = 0; i < n; ++i) { p[i] = rand_(); } } else { for (r = 1, i = 0; i < n; ++i) { p[i] = KnuthLinearCongruentialGenerator(&r) >> 32 | KnuthLinearCongruentialGenerator(&r) >> 32 << 32; } } return p; } static long double ConvertRange(long double x, long double a, long double b, long double c, long double d) { return (d - c) / (b - a) * (x - a) + c; } static double Compand(long x, double a, double b, double c, double d) { return ConvertRange(ConvertRange(x, LONG_MIN, LONG_MAX, a, b), a, b, c, d); } static void GenerateMatrixImpl(long I[yn_][xn_], double M[yn_][xn_], FILE *f) { long y, x; for (y = 0; y < yn_; ++y) { for (x = 0; x < xn_; ++x) { M[y][x] = Compand(I[y][x], r1_.a, r1_.b, r2_.a, r2_.b); } if (rounder_) { for (x = 0; x < xn_; ++x) { M[y][x] = rounder_(M[y][x]); } } } FormatMatrixDouble(yn_, xn_, M, fputs, f, formatter_, type_, name_, NULL, digs_, round); } void GenerateMatrix(FILE *f) { GenerateMatrixImpl(SetRandom(yn_ * xn_, gc(calloc(yn_ * xn_, sizeof(long)))), gc(calloc(yn_ * xn_, sizeof(double))), f); } int main(int argc, char *argv[]) { int i; FILE *f; ShowCrashReports(); GetOpts(argc, argv); CHECK_NOTNULL((f = fopen(path_, "w"))); if (optind < argc) FATALF("TODO(jart): support input files"); GenerateMatrix(f); return fclose(f); }
9,853
316
jart/cosmopolitan
false
cosmopolitan/tool/viz/printdos2errno.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/fmt.h" #include "libc/intrin/dos2errno.internal.h" #include "libc/intrin/kprintf.h" #include "libc/str/str.h" // note: these are supplementary errno magnum mappings // don't include the ones in libc/sysv/consts.sh int main(int argc, char *argv[]) { int i; for (i = 0; kDos2Errno[i].doscode; ++i) { kprintf("dos error %10hu maps to rva %10d errno %10d which is %s%n", kDos2Errno[i].doscode, kDos2Errno[i].systemv, *(const int *)((intptr_t)kDos2Errno + kDos2Errno[i].systemv), _strerrno( *(const int *)((intptr_t)kDos2Errno + kDos2Errno[i].systemv))); } return 0; }
2,491
38
jart/cosmopolitan
false
cosmopolitan/tool/viz/xterm256cubes.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/assert.h" #include "libc/stdio/stdio.h" #define DIST(X, Y) ((X) - (Y)) #define SQR(X) ((X) * (X)) #define SUM(X, Y, Z) ((X) + (Y) + (Z)) static const uint8_t kXtermCube[] = {0, 0137, 0207, 0257, 0327, 0377}; static int uncube(int x) { return x < 48 ? 0 : x < 115 ? 1 : (x - 35) / 40; } static int rgb2xterm256(int r, int g, int b) { unsigned av, ir, ig, ib, il, qr, qg, qb, ql; av = (r + g + b) / 3; ql = (il = av > 238 ? 23 : (av - 3) / 10) * 10 + 8; qr = kXtermCube[(ir = uncube(r))]; qg = kXtermCube[(ig = uncube(g))]; qb = kXtermCube[(ib = uncube(b))]; if (SUM(SQR(DIST(qr, r)), SQR(DIST(qg, g)), SQR(DIST(qb, b))) <= SUM(SQR(DIST(ql, r)), SQR(DIST(ql, g)), SQR(DIST(ql, b)))) { return ir * 36 + ig * 6 + ib + 020; } else { return il + 0350; } } bool IsUglyColorMixture(int rune, int y, int tone, bool toneisfg) { assert(tone == 16 || (231 <= tone && tone <= 255)); return false; } int main(int argc, char *argv[]) { unsigned y, z, x, k, w; static const char16_t s[2][3] = {{u'▓', u'▒', u'░'}, {u'░', u'▒', u'▓'}}; printf("\npure\n"); for (y = 0; y < 6; ++y) { for (z = 0; z < 6; ++z) { for (x = 0; x < 6; ++x) { printf("\033[48;5;%hhum ", 16 + x + y * 6 + z * 6 * 6); } printf("\033[0m "); } printf("\n"); } #define MIX(NAME, COLOR) \ do { \ printf("\n%s %d ▓░/▒▒/░▓\n", NAME, COLOR); \ for (k = 0; k < 3; ++k) { \ for (y = 0; y < 6; ++y) { \ for (z = 0; z < 6; ++z) { \ for (x = 0; x < 6; ++x) { \ printf("\033[48;5;%hhu;38;5;%hhum%lc", COLOR, \ 16 + x + y * 6 + z * 6 * 6, s[0][k]); \ printf("\033[48;5;%hhu;38;5;%hhum%lc", 16 + x + y * 6 + z * 6 * 6, \ COLOR, s[1][k]); \ } \ printf("\033[0m "); \ } \ printf("\n"); \ } \ } \ } while (0) MIX("tint", 231); MIX("tint", 255); MIX("tint", 254); MIX("tone", 240); MIX("shade", 232); for (w = 233; w < 254; ++w) { MIX("gray", w); } return 0; }
4,756
98
jart/cosmopolitan
false
cosmopolitan/tool/viz/printpixel.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 "dsp/tty/quant.h" #include "dsp/tty/xtermname.h" #include "libc/fmt/conv.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" int main(int argc, char *argv[]) { int i; struct TtyRgb tty; unsigned rgb, r, g, b; if (argc < 2) { fprintf(stderr, "Usage: %s RRGGBB...\n", program_invocation_name); exit(EX_USAGE); } for (i = 1; i < argc; ++i) { rgb = strtol(argv[i], NULL, 16); b = (rgb & 0x0000ff) >> 000; g = (rgb & 0x00ff00) >> 010; r = (rgb & 0xff0000) >> 020; tty = rgb2tty(r, g, b); printf("\e[48;5;%dm \e[0m %d \\e[48;5;%dm %s #%02x%02x%02x\n", tty.xt, tty.xt, tty.xt, IndexDoubleNulString(kXtermName, tty.xt), r, g, b); } return 0; }
2,618
46
jart/cosmopolitan
false
cosmopolitan/tool/viz/double2int.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/limits.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/x/x.h" #include "third_party/gdtoa/gdtoa.h" void double2int(const char *s) { double b64; uint64_t u64; b64 = strtod(s, NULL); memcpy(&u64, &b64, 8); printf("0x%016lx\n", u64); } int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; ++i) { double2int(argv[i]); } return 0; }
2,335
43
jart/cosmopolitan
false
cosmopolitan/tool/viz/upscaleint.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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/x/x.h" #include "third_party/stb/stb_image.h" #define CLAMP(X) MAX(0, MIN(255, X)) #define C13(A, B) (((A) + 3 * (B) + 2) >> 2) #define S3T(A, B, C) CLAMP(-((A) >> 2) + ((B) + ((B) >> 1)) + -((C) >> 2)) #define LERP(X, Y, P) ((X) + (((P) * ((Y) - (X))) >> 8)) static unsigned char ChessBoard(unsigned y, unsigned x, unsigned char a, unsigned char b) { return !((y ^ x) & (1u << 2)) ? a : b; } static unsigned char AlphaBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 255, 200); } static unsigned char OutOfBoundsBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 40, 80); } static unsigned char Opacify(size_t yn, size_t xn, const unsigned char P[yn][xn], const unsigned char A[yn][xn], long y, long x) { if ((0 <= y && y < yn) && (0 <= x && x < xn)) { return LERP(AlphaBackground(y, x), P[y][x], A[y][x]); } else { return OutOfBoundsBackground(y, x); } } static void PrintImage(size_t yn, size_t xn, unsigned char R[yn][xn], unsigned char G[yn][xn], unsigned char B[yn][xn], unsigned char A[yn][xn]) { unsigned y, x; for (y = 0; y < yn; y += 2) { if (y) printf("\e[0m\n"); for (x = 0; x < xn; ++x) { printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄", Opacify(yn, xn, R, A, y + 0, x), Opacify(yn, xn, G, A, y + 0, x), Opacify(yn, xn, B, A, y + 0, x), Opacify(yn, xn, R, A, y + 1, x), Opacify(yn, xn, G, A, y + 1, x), Opacify(yn, xn, B, A, y + 1, x)); } } printf("\e[0m\n"); } static void DeblinterlaceRgba(size_t dyn, size_t dxn, unsigned char R[dyn][dxn], unsigned char G[dyn][dxn], unsigned char B[dyn][dxn], unsigned char A[dyn][dxn], size_t syn, size_t sxn, const unsigned char src[syn][sxn][4]) { unsigned y, x; for (y = 0; y < syn; ++y) { for (x = 0; x < sxn; ++x) { R[y][x] = src[y][x][0]; G[y][x] = src[y][x][1]; B[y][x] = src[y][x][2]; A[y][x] = src[y][x][3]; } } } static void SharpenX(size_t yw, size_t xw, unsigned char dst[yw][xw], const unsigned char src[yw][xw], size_t yn, size_t xn) { int y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { dst[y][x] = S3T(src[y][MAX(0, x - 1)], src[y][x], src[y][MIN(xn - 1, x + 1)]); } } } static void SharpenY(size_t yw, size_t xw, unsigned char dst[yw][xw], const unsigned char src[yw][xw], size_t yn, size_t xn) { int y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { dst[y][x] = S3T(src[MAX(0, y - 1)][x], src[y][x], src[MIN(yn - 1, y + 1)][x]); } } } static void UpscaleX(size_t yw, size_t xw, unsigned char img[yw][xw], size_t yn, size_t xn) { unsigned y, x; for (y = yn; y--;) { for (x = xn; --x;) { img[y][x] = C13(img[y][MIN(xn / 2 - 1, x / 2 - 1 + x % 2 * 2)], img[y][x / 2]); } } } static void UpscaleY(size_t yw, size_t xw, unsigned char img[yw][xw], size_t yn, size_t xn) { unsigned y, x; for (y = yn; --y;) { for (x = xn; x--;) { img[y][x] = C13(img[MIN(yn / 2 - 1, y / 2 - 1 + y % 2 * 2)][x], img[y / 2][x]); } } } static void Upscale(size_t yw, size_t xw, unsigned char img[yw][xw], unsigned char tmp[yw][xw], size_t yn, size_t xn) { UpscaleY(yw, xw, img, yn, xn / 2); SharpenY(yw, xw, tmp, img, yn, xn / 2); UpscaleX(yw, xw, tmp, yn, xn); SharpenX(yw, xw, img, tmp, yn, xn); } static void ProcessImageDouble(size_t yn, size_t xn, unsigned char img[yn][xn][4]) { void *t = xmemalign(32, sizeof(unsigned char) * yn * 2 * xn * 2); void *R = xmemalign(32, sizeof(unsigned char) * yn * 2 * xn * 2); void *G = xmemalign(32, sizeof(unsigned char) * yn * 2 * xn * 2); void *B = xmemalign(32, sizeof(unsigned char) * yn * 2 * xn * 2); void *A = xmemalign(32, sizeof(unsigned char) * yn * 2 * xn * 2); DeblinterlaceRgba(yn * 2, xn * 2, R, G, B, A, yn, xn, img); Upscale(yn * 2, xn * 2, R, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, G, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, B, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, A, t, yn * 2, xn * 2); free(t); PrintImage(yn * 2, xn * 2, R, G, B, A); free(R); free(G); free(B); free(A); } static void ProcessImage(size_t yn, size_t xn, unsigned char img[yn][xn][4]) { void *R = xmemalign(32, sizeof(unsigned char) * yn * xn); void *G = xmemalign(32, sizeof(unsigned char) * yn * xn); void *B = xmemalign(32, sizeof(unsigned char) * yn * xn); void *A = xmemalign(32, sizeof(unsigned char) * yn * xn); DeblinterlaceRgba(yn, xn, R, G, B, A, yn, xn, img); PrintImage(yn, xn, R, G, B, A); free(R); free(G); free(B); free(A); } void WithImageFile(const char *path, void fn(size_t yn, size_t xn, unsigned char img[yn][xn][4])) { struct stat st; int fd, yn, xn; void *map, *data; CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_GT(st.st_size, 0); CHECK_LE(st.st_size, INT_MAX); fadvise(fd, 0, 0, MADV_WILLNEED | MADV_SEQUENTIAL); CHECK_NE(MAP_FAILED, (map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))); CHECK_NOTNULL( (data = stbi_load_from_memory(map, st.st_size, &xn, &yn, NULL, 4)), "%s", path); CHECK_NE(-1, munmap(map, st.st_size)); CHECK_NE(-1, close(fd)); fn(yn, xn, data); free(data); } int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; ++i) { WithImageFile(argv[i], ProcessImageDouble); } return 0; }
8,145
210
jart/cosmopolitan
false
cosmopolitan/tool/viz/upscalefloat.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/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/x/x.h" #include "third_party/stb/stb_image.h" #define C13(A, B) (((A) + 3 * (B)) / 4) #define S3T(A, B, C) MAX(0, ((24 * (B)) - (4 * ((A) + (C)))) / 16) #define LERP(A, B, P) ((A) * (1 - (P)) + (B) * (P)) float ByteToFloat(int b) { return 1 / 255.f * b; } int FloatToByte(float f) { return MAX(0, MIN(255, roundf(255 * f))); } float ChessBoard(unsigned y, unsigned x, float a, float b) { return !((y ^ x) & (1u << 2)) ? a : b; } float AlphaBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 1.f, .7f); } float OutOfBoundsBackground(unsigned y, unsigned x) { return ChessBoard(y, x, .01f, .02f); } float Opacify(size_t yn, size_t xn, const float P[yn][xn], const float A[yn][xn], long y, long x) { if ((0 <= y && y < yn) && (0 <= x && x < xn)) { return LERP(AlphaBackground(y, x), P[y][x], A[y][x]); } else { return OutOfBoundsBackground(y, x); } } void PrintImage(size_t yn, size_t xn, float R[yn][xn], float G[yn][xn], float B[yn][xn], float A[yn][xn]) { unsigned y, x; for (y = 0; y < yn; y += 2) { if (y) printf("\e[0m\n"); for (x = 0; x < xn; ++x) { printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm▄", FloatToByte(Opacify(yn, xn, R, A, y + 0, x)), FloatToByte(Opacify(yn, xn, G, A, y + 0, x)), FloatToByte(Opacify(yn, xn, B, A, y + 0, x)), FloatToByte(Opacify(yn, xn, R, A, y + 1, x)), FloatToByte(Opacify(yn, xn, G, A, y + 1, x)), FloatToByte(Opacify(yn, xn, B, A, y + 1, x))); } } printf("\e[0m\n"); } void DeblinterlaceRgba(size_t dyn, size_t dxn, float R[dyn][dxn], float G[dyn][dxn], float B[dyn][dxn], float A[dyn][dxn], size_t syn, size_t sxn, const unsigned char src[syn][sxn][4]) { unsigned y, x; for (y = 0; y < syn; ++y) { for (x = 0; x < sxn; ++x) { R[y][x] = ByteToFloat(src[y][x][0]); G[y][x] = ByteToFloat(src[y][x][1]); B[y][x] = ByteToFloat(src[y][x][2]); A[y][x] = ByteToFloat(src[y][x][3]); } } } void SharpenX(size_t yw, size_t xw, float dst[yw][xw], const float src[yw][xw], size_t yn, size_t xn) { int y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { dst[y][x] = S3T(src[y][MAX(0, x - 1)], src[y][x], src[y][MIN(xn - 1, x + 1)]); } } } void SharpenY(size_t yw, size_t xw, float dst[yw][xw], const float src[yw][xw], size_t yn, size_t xn) { int y, x; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { dst[y][x] = S3T(src[MAX(0, y - 1)][x], src[y][x], src[MIN(yn - 1, y + 1)][x]); } } } void UpscaleX(size_t yw, size_t xw, float img[yw][xw], size_t yn, size_t xn) { unsigned y, x; for (y = yn; y--;) { for (x = xn; --x;) { img[y][x] = C13(img[y][MIN(xn / 2 - 1, x / 2 - 1 + x % 2 * 2)], img[y][x / 2]); } } } void UpscaleY(size_t yw, size_t xw, float img[yw][xw], size_t yn, size_t xn) { unsigned y, x; for (y = yn; --y;) { for (x = xn; x--;) { img[y][x] = C13(img[MIN(yn / 2 - 1, y / 2 - 1 + y % 2 * 2)][x], img[y / 2][x]); } } } void Upscale(size_t yw, size_t xw, float img[yw][xw], float tmp[yw][xw], size_t yn, size_t xn) { UpscaleY(yw, xw, img, yn, xn / 2); SharpenY(yw, xw, tmp, img, yn, xn / 2); UpscaleX(yw, xw, tmp, yn, xn); SharpenX(yw, xw, img, tmp, yn, xn); } void ProcessImageDouble(size_t yn, size_t xn, unsigned char img[yn][xn][4]) { void *t = xmemalign(32, sizeof(float) * yn * 2 * xn * 2); void *R = xmemalign(32, sizeof(float) * yn * 2 * xn * 2); void *G = xmemalign(32, sizeof(float) * yn * 2 * xn * 2); void *B = xmemalign(32, sizeof(float) * yn * 2 * xn * 2); void *A = xmemalign(32, sizeof(float) * yn * 2 * xn * 2); DeblinterlaceRgba(yn * 2, xn * 2, R, G, B, A, yn, xn, img); Upscale(yn * 2, xn * 2, R, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, G, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, B, t, yn * 2, xn * 2); Upscale(yn * 2, xn * 2, A, t, yn * 2, xn * 2); free(t); PrintImage(yn * 2, xn * 2, R, G, B, A); free(R); free(G); free(B); free(A); } void ProcessImage(size_t yn, size_t xn, unsigned char img[yn][xn][4]) { void *R = xmemalign(32, sizeof(float) * yn * xn); void *G = xmemalign(32, sizeof(float) * yn * xn); void *B = xmemalign(32, sizeof(float) * yn * xn); void *A = xmemalign(32, sizeof(float) * yn * xn); DeblinterlaceRgba(yn, xn, R, G, B, A, yn, xn, img); PrintImage(yn, xn, R, G, B, A); free(R); free(G); free(B); free(A); } void WithImageFile(const char *path, void fn(size_t yn, size_t xn, unsigned char img[yn][xn][4])) { struct stat st; int fd, yn, xn; void *map, *data; CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_GT(st.st_size, 0); CHECK_LE(st.st_size, INT_MAX); fadvise(fd, 0, 0, MADV_WILLNEED | MADV_SEQUENTIAL); CHECK_NE(MAP_FAILED, (map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))); CHECK_NOTNULL( (data = stbi_load_from_memory(map, st.st_size, &xn, &yn, NULL, 4)), "%s", path); CHECK_NE(-1, munmap(map, st.st_size)); CHECK_NE(-1, close(fd)); fn(yn, xn, data); free(data); } int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; ++i) { WithImageFile(argv[i], ProcessImageDouble); } return 0; }
7,780
213
jart/cosmopolitan
false
cosmopolitan/tool/viz/maxmind.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 "libc/calls/calls.h" #include "libc/intrin/bits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "net/http/http.h" #include "net/http/ip.h" #include "third_party/maxmind/maxminddb.h" #define PATH(...) \ (const char *const[]) { \ __VA_ARGS__, 0 \ } MMDB_s *ipdb, *asdb; int PrintIpInfo(const char *ipstr) { int error; bool uhoh; int64_t ip; uint16_t cc; MMDB_entry_data_s e, f; MMDB_lookup_result_s r; if ((ip = ParseIp(ipstr, -1)) == -1) { fprintf(stderr, "BAD IP: %s\n", ipstr); return -1; } r = MMDB_lookup(ipdb, ip, &error); CHECK_EQ(MMDB_SUCCESS, error); if (!r.found_entry) { fprintf(stderr, "NOT FOUND: %s\n", ipstr); return -1; } printf("%hhu.%hhu.%hhu.%hhu\n", ip >> 24, ip >> 16, ip >> 8, ip); if (!MMDB_aget_value(&r.entry, &e, PATH("location", "metro_code"))) { printf("%s: %s\n", "metro", GetMetroName(e.uint16)); } if (!MMDB_aget_value(&r.entry, &e, PATH("postal", "code"))) { printf("%s: %.*s\n", "postal", e.data_size, e.utf8_string); } if (!MMDB_aget_value(&r.entry, &e, PATH("city", "names", "en"))) { printf("%s: %.*s\n", "city", e.data_size, e.utf8_string); } if (!MMDB_aget_value(&r.entry, &e, PATH("subdivisions", "0", "iso_code")) && !MMDB_aget_value(&r.entry, &f, PATH("subdivisions", "0", "names", "en"))) { printf("%s: %.*s (%.*s)\n", "region", e.data_size, e.utf8_string, f.data_size, f.utf8_string); } if (!MMDB_aget_value(&r.entry, &e, PATH("country", "iso_code")) && !MMDB_aget_value(&r.entry, &f, PATH("country", "names", "en"))) { printf("%s: %.*s (%.*s)\n", "country", e.data_size, e.utf8_string, f.data_size, f.utf8_string); cc = READ16LE(e.utf8_string); } else { cc = 0; } if (!MMDB_aget_value(&r.entry, &e, PATH("registered_country", "iso_code")) && !MMDB_aget_value(&r.entry, &f, PATH("registered_country", "names", "en"))) { uhoh = cc && cc != READ16LE(e.utf8_string); printf("%s%s: %.*s (%.*s)%s\n", uhoh ? "\e[1m" : "", "registered", e.data_size, e.utf8_string, f.data_size, f.utf8_string, uhoh ? "\e[0m" : ""); } if ((!MMDB_aget_value(&r.entry, &e, PATH("country", "is_in_european_union")) && e.boolean) || (!MMDB_aget_value(&r.entry, &e, PATH("registered_country", "is_in_european_union")) && e.boolean)) { printf("%s: %s\n", "is_in_european_union", "true"); } if (!MMDB_aget_value(&r.entry, &e, PATH("continent", "code")) && !MMDB_aget_value(&r.entry, &f, PATH("continent", "names", "en"))) { printf("%s: %.*s (%.*s)\n", "continent", e.data_size, e.utf8_string, f.data_size, f.utf8_string); } if (!MMDB_aget_value(&r.entry, &e, PATH("location", "time_zone"))) { printf("%s: %.*s\n", "timezone", e.data_size, e.utf8_string); } if (!MMDB_aget_value(&r.entry, &e, PATH("location", "latitude")) && !MMDB_aget_value(&r.entry, &f, PATH("location", "longitude"))) { printf("%s: %g %g\n", "location", e.double_value, f.double_value); } if (!MMDB_aget_value(&r.entry, &e, PATH("location", "accuracy_radius"))) { printf("%s: %dkm\n", "accuracy", e.uint16); } printf("%s: %s\n", "category", GetIpCategoryName(CategorizeIp(ip))); if ((r = MMDB_lookup(asdb, ip, &error)).found_entry && !MMDB_aget_value(&r.entry, &e, PATH("autonomous_system_number")) && !MMDB_aget_value(&r.entry, &f, PATH("autonomous_system_organization"))) { printf("%s: AS%u (%.*s)\n", "asn", e.uint32, f.data_size, f.utf8_string); } return 0; } int main(int argc, char *argv[]) { int i, rc; ipdb = gc(calloc(1, sizeof(MMDB_s))); CHECK_EQ(MMDB_SUCCESS, MMDB_open("/usr/local/share/maxmind/GeoLite2-City.mmdb", 0, ipdb)); asdb = gc(calloc(1, sizeof(MMDB_s))); CHECK_EQ(MMDB_SUCCESS, MMDB_open("/usr/local/share/maxmind/GeoLite2-ASN.mmdb", 0, asdb)); for (rc = 0, i = 1; i < argc; ++i) { if (PrintIpInfo(argv[i]) != -1) { if (i + 1 < argc) printf("\n"); } else { fprintf(stderr, "NOT FOUND: %s\n", argv[i]); rc = 1; } } MMDB_close(asdb); MMDB_close(ipdb); return rc; }
6,184
138
jart/cosmopolitan
false
cosmopolitan/tool/viz/echoctl.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/struct/termios.h" #include "libc/calls/termios.h" #include "libc/sysv/consts/termios.h" int main(int argc, char *argv[]) { struct termios t; if (tcgetattr(0, &t) == -1) return 1; t.c_lflag ^= ECHOCTL; if (tcsetattr(0, TCSANOW, &t) == -1) return 2; }
2,116
29
jart/cosmopolitan
false
cosmopolitan/tool/viz/memplan.c
#if 0 /*─────────────────────────────────────────────────────────────────╗ │ To the extent possible under law, Justine Tunney has waived │ │ all copyright and related or neighboring rights to this file, │ │ as it is written in the following disclaimers: │ │ • http://unlicense.org/ │ │ • http://creativecommons.org/publicdomain/zero/1.0/ │ ╚─────────────────────────────────────────────────────────────────*/ #endif #include "libc/calls/internal.h" #include "libc/fmt/conv.h" #include "libc/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/macros.internal.h" #include "libc/runtime/memtrack.internal.h" #include "libc/stdio/stdio.h" // clang-format off struct WinArgs { char *argv[4096]; char *envp[4092]; intptr_t auxv[2][2]; char argblock[ARG_MAX / 2]; char envblock[ARG_MAX / 2]; }; //#define INCREMENT _roundup2pow(kAutomapSize/16) #define INCREMENT (64L*1024*1024*1024) uint64_t last; void plan2(uint64_t addr, uint64_t end, const char *name) { char sz[32]; sizefmt(sz, end-addr+1, 1024); printf("%08x-%08x %-6s %s\n", addr>>16, end>>16, sz, name); } void plan(uint64_t addr, uint64_t end, const char *name) { uint64_t incr, next; while (addr > last) { if ((incr = last % INCREMENT)) { incr = INCREMENT - incr; } else { incr = INCREMENT; } plan2(last,MIN(last+incr,addr)-1,"free"); last = MIN(last+incr,addr); } while (addr <= end) { if (end-addr+1 <= INCREMENT) { plan2(addr,end,name); last = end + 1; break; } if (!(addr % INCREMENT)) { plan2(addr, addr + INCREMENT - 1, name); last = addr + INCREMENT; addr += INCREMENT; } else { next = INCREMENT - addr % INCREMENT + addr; plan2(addr, next - 1, name); last = next; addr = next; } } } int main(int argc, char *argv[]) { uint64_t x, y; plan(0x00000000, 0x00200000-1, "null"); plan(0x00200000, 0x00400000-1, "loader"); if (!IsWindows() || IsAtLeastWindows10()) { plan(0x00400000, 0x50000000-1, "image"); plan(0x50000000, 0x7ffdffff, "arena"); plan(0x7fff0000, 0x10007fffffff, "asan"); } else { plan(0x00400000, 0x01000000-1, "image"); } plan(kAutomapStart, kAutomapStart + kAutomapSize - 1, "automap"); plan(kMemtrackStart, kMemtrackStart + kMemtrackSize - 1, "memtrack"); plan(kFixedmapStart, kFixedmapStart + kFixedmapSize - 1, "fixedmap"); if (IsWindows() && !IsAtLeastWindows10()) { plan(0x50000000, 0x7ffdffff, "arena"); } x = GetStaticStackAddr(0); y = ROUNDUP(sizeof(struct WinArgs), FRAMESIZE); plan(x - y, x - 1, "winargs"); plan(x, x + GetStackSize() - 1, "stack"); if (!IsWindows() || IsAtLeastWindows10()) { plan(0x7f0000000000, 0x800000000000 - 1, "kernel"); } return 0; }
3,124
96
jart/cosmopolitan
false
cosmopolitan/tool/viz/bf.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 "libc/calls/calls.h" #include "libc/calls/struct/stat.h" #include "libc/fmt/itoa.h" #include "libc/intrin/bits.h" #include "libc/intrin/bsr.h" #include "libc/intrin/tpenc.h" #include "libc/macros.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/s.h" /** * @fileoverview BingFold - A Hexdump Tool */ #define W 64 #define C 253 void bf(int fd) { ssize_t rc; uint64_t w; struct stat st; size_t i, n, o; int c, fg, fg2, bits; char ibuf[W], obuf[12 + 1 + W * 6 + 1 + W * (2 + 11) + 11 + 1]; o = 0; if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode) && st.st_size) { bits = _bsr(_roundup2pow(st.st_size)); bits = ROUNDUP(bits, 4); } else { bits = 48; } do { if ((rc = read(fd, ibuf, W)) == -1) exit(2); if (rc) { n = 0; n += uint64toarray_fixed16(o, obuf + n, bits); o += rc; obuf[n++] = ' '; for (i = 0; i < rc; ++i) { c = ibuf[i] & 0xff; w = _tpenc(kCp437[c]); do { obuf[n++] = w; } while ((w >>= 8)); } for (i = 0; i < W - rc + 1; ++i) { obuf[n++] = ' '; } for (fg = -1, i = 0; i < rc; ++i) { c = ibuf[i] & 0xff; if (c < 32) { fg2 = 237 + c * ((C - 237) / 32.); } else if (c >= 232) { fg2 = C + (c - 232) * ((255 - C) / (256. - 232)); } else { fg2 = C; } if (fg2 != fg) { fg = fg2; obuf[n++] = 033; obuf[n++] = '['; obuf[n++] = '3'; obuf[n++] = '8'; obuf[n++] = ';'; obuf[n++] = '5'; obuf[n++] = ';'; n = FormatInt64(obuf + n, fg) - (obuf + n); obuf[n++] = 'm'; } obuf[n++] = "0123456789abcdef"[c >> 4]; obuf[n++] = "0123456789abcdef"[c & 15]; /* obuf[n++] = ' '; */ } obuf[n++] = 033; obuf[n++] = '['; obuf[n++] = '0'; obuf[n++] = 'm'; obuf[n++] = '\n'; write(1, obuf, n); } } while (rc == W); } int main(int argc, char *argv[]) { int i, fd; if (argc > 1) { for (i = 1; i < argc; ++i) { if (i > 1) write(1, "\n", 1); if ((fd = open(argv[i], O_RDONLY)) == -1) exit(1); bf(fd); } } else { bf(0); } return 0; }
4,215
118
jart/cosmopolitan
false
cosmopolitan/tool/viz/bin2asm.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/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #define COLS 8 int main(int argc, char *argv[]) { int c, col = 0; int need_newline = 0; char16_t glyphs[COLS + 1]; while ((c = getchar()) != -1) { if (!col) { need_newline = 1; printf("\t.byte\t"); bzero(glyphs, sizeof(glyphs)); } glyphs[col] = kCp437[c]; if (col) putchar(','); printf("0x%02x", c); if (++col == COLS) { col = 0; printf("\t//%hs\n", glyphs); need_newline = 0; } } if (need_newline) { printf("\n"); } return 0; }
2,442
49
jart/cosmopolitan
false
cosmopolitan/tool/viz/od16.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/fmt/fmt.h" #include "libc/log/check.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [FLAGS] [PATH...]\n\ this program prints binary as signed 16-bit decimal numbers\n\ \n\ Flags:\n\ -n INT\n\ -c INT\n\ -w INT width (aka cols) [default 8]\n\ -o PATH output path [default -]\n\ -h shows this information\n\ \n" static long width_; static FILE *in_, *out_; static char *inpath_, *outpath_; void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void GetOpts(int *argc, char *argv[]) { int opt; outpath_ = "-"; while ((opt = getopt(*argc, argv, "?ho:w:c:n:")) != -1) { switch (opt) { case 'o': outpath_ = optarg; break; case 'n': case 'c': case 'w': width_ = strtol(optarg, NULL, 0); break; case '?': case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } if (optind == *argc) { argv[(*argc)++] = "-"; } } void ProcessFile(void) { int a, b; unsigned n; n = 0; while ((a = fgetc(in_)) != -1 && (b = fgetc(in_)) != -1) { if (n) { fputc(',', out_); fputc(' ', out_); } fprintf(out_, "%7hd", b << 010 | a); if (++n == width_) { n = 0; fputc('\n', out_); } } if (n) { fputc('\n', out_); } } int main(int argc, char *argv[]) { size_t i; GetOpts(&argc, argv); CHECK_NOTNULL((out_ = fopen(outpath_, "w"))); for (i = optind; i < argc; ++i) { CHECK_NOTNULL((in_ = fopen((inpath_ = argv[i]), "r"))); ProcessFile(); CHECK_NE(-1, fclose(in_)); in_ = 0; } CHECK_NE(-1, fclose(out_)); out_ = 0; return 0; }
3,808
112
jart/cosmopolitan
false
cosmopolitan/tool/viz/fliphex.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 "libc/fmt/conv.h" #include "libc/stdio/stdio.h" int main(int argc, char *argv[]) { int i, x; for (i = 1; i < argc; ++i) { x = strtoul(argv[i], 0, 0); printf("%#x\n", -x); } return 0; }
2,047
30
jart/cosmopolitan
false
cosmopolitan/tool/viz/getglyph.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 "libc/calls/struct/sigaction.h" #include "libc/fmt/conv.h" #include "libc/intrin/tpenc.h" #include "libc/limits.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/stdio/append.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/sig.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_truetype.h" #define SQR(x) ((x) * (x)) int end; int start; int verbose; int difference; struct Block { char16_t c; unsigned char b[4][2]; } kBlocks[] = { {u' ', {{0000, 0000}, {0000, 0000}, {0000, 0000}, {0000, 0000}}}, // {u'░', {{0060, 0060}, {0060, 0060}, {0060, 0060}, {0060, 0060}}}, // {u'▒', {{0140, 0140}, {0140, 0140}, {0140, 0140}, {0140, 0140}}}, // {u'▓', {{0300, 0300}, {0300, 0300}, {0300, 0300}, {0300, 0300}}}, // {u'█', {{0377, 0377}, {0377, 0377}, {0377, 0377}, {0377, 0377}}}, // {u'▄', {{0000, 0000}, {0000, 0000}, {0377, 0377}, {0377, 0377}}}, // {u'▌', {{0377, 0000}, {0377, 0000}, {0377, 0000}, {0377, 0000}}}, // {u'▐', {{0000, 0377}, {0000, 0377}, {0000, 0377}, {0000, 0377}}}, // {u'▀', {{0377, 0377}, {0377, 0377}, {0000, 0000}, {0000, 0000}}}, // }; static char *Raster(int yn, int xn, unsigned char Y[yn][xn], int *dw) { char *r = 0; unsigned char B[4][4]; int y, x, i, j, k, s, w, bi, bs; *dw = 0; for (y = 0; y < yn; y += 4) { if (y) appendw(&r, '\n'); for (w = x = 0; x < xn; x += 4) { for (i = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) { if (y + i < yn && x + j < xn) { B[i][j] = Y[y + i][x + j]; } else { B[i][j] = 0; } } } bi = 0; bs = INT_MAX; for (k = 0; k < ARRAYLEN(kBlocks); ++k) { s = 0; for (i = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) { s += SQR(B[i][j] - kBlocks[k].b[i][j / 2]); } } if (s < bs) { bi = k; bs = s; } } appendw(&r, _tpenc(kBlocks[bi].c)); ++w; } if (w > *dw) *dw = w; } return r; } void OnSig(int sig) { exit(128 + sig); } int main(int argc, char *argv[]) { char *p; void *bmap; float scale; bool gotsome; char **rasters; char **fasters; size_t ttfsize; const char *dir; bool isdifferent; unsigned char **ttf; stbtt_fontinfo *font; int c, i, j, m, o, dw, maxw, *w, *h, s = 40 * 4; ShowCrashReports(); signal(SIGPIPE, OnSig); start = 0; end = 0x10FFFD; while ((o = getopt(argc, argv, "vdc:s:e:S:")) != -1) { switch (o) { case 'v': ++verbose; break; case 'd': difference = 1; break; case 'c': start = end = strtol(optarg, 0, 16); break; case 's': start = strtol(optarg, 0, 16); break; case 'e': end = strtol(optarg, 0, 16); break; case 'S': s = strtol(optarg, 0, 0); break; default: return 1; } } m = argc - optind; w = _gc(calloc(m, sizeof(*w))); h = _gc(calloc(m, sizeof(*h))); ttf = _gc(calloc(m, sizeof(*ttf))); font = _gc(calloc(m, sizeof(*font))); rasters = _gc(calloc(m, sizeof(*rasters))); fasters = _gc(calloc(m, sizeof(*fasters))); for (j = 0; j < m; ++j) { ttf[j] = _gc(xslurp(argv[optind + j], &ttfsize)); if (!ttf[j]) { fprintf(stderr, "%s: not found\n", argv[optind + j]); exit(1); } stbtt_InitFont(font + j, ttf[j], stbtt_GetFontOffsetForIndex(ttf[j], 0)); printf("%s\n", argv[optind + j]); } for (c = start; c <= end; ++c) { maxw = 0; gotsome = false; isdifferent = false; for (j = 0; j < m; ++j) { rasters[j] = 0; if ((i = stbtt_FindGlyphIndex(font + j, c)) > 0) { w[j] = 0; h[j] = 0; scale = stbtt_ScaleForPixelHeight(font + j, s); bmap = stbtt_GetGlyphBitmap(font + j, 0, scale, i, w + j, h + j, 0, 0); if (w[j] && h[j]) { gotsome = true; if (verbose) { rasters[j] = Raster(h[j], w[j], bmap, &dw); if (!isdifferent && j && rasters[j - 1] && strcmp(rasters[j], rasters[j - 1])) { isdifferent = true; } if (dw > maxw) maxw = dw; } } free(bmap); } } if (gotsome) { memcpy(fasters, rasters, m * sizeof(*rasters)); printf("%04X\n", c); if (verbose && (!difference || isdifferent)) { do { gotsome = false; for (j = 0; j < m; ++j) { if (!rasters[j]) { printf("%-*s ", maxw, ""); continue; } p = strchrnul(rasters[j], '\n'); if (p - rasters[j]) gotsome = true; printf("%-*.*s ", maxw, p - rasters[j], rasters[j]); rasters[j] = *p ? p + 1 : p; } printf("\n"); } while (gotsome); printf("\n"); } for (j = 0; j < m; ++j) { free(fasters[j]); } } } return 0; }
6,990
209
jart/cosmopolitan
false
cosmopolitan/tool/viz/fontspace.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 "dsp/scale/cdecimate2xuint8x8.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/winsize.h" #include "libc/fmt/conv.h" #include "libc/intrin/bsr.h" #include "libc/log/libfatal.internal.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/termios.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_truetype.h" #define MAXCODE int start; int end = 0x03134A /* 0x10FFFD */; int verbose; struct winsize ws = {24, 80}; signed char kThePerfectKernel[8] = {-1, -3, 3, 17, 17, 3, -3, -1}; void PrintBar(unsigned char *p, size_t n) { size_t i, j; for (j = n; j > ws.ws_col - 32; j = (j + 1) >> 1) { cDecimate2xUint8x8(j, p, kThePerfectKernel); } for (i = 0; i < j; ++i) { if (p[i]) { fputwc(u"░░▒▒▓▓██"[_bsr(p[i])], stdout); } else { fputc(' ', stdout); } } } int main(int argc, char *argv[]) { size_t n, m; float scale; void *bitmap; size_t ttfsize; const char *dir; unsigned char *ttf; stbtt_fontinfo font; unsigned char *present; unsigned char *intotal; int w, h, i, j, c, arg, opt, errs, line, count, maxcode, s = 40 * 4, rc = 0; ShowCrashReports(); ioctl(0, TIOCGWINSZ, &ws); while ((opt = getopt(argc, argv, "vs:e:")) != -1) { switch (opt) { case 'v': ++verbose; break; case 's': start = strtol(optarg, 0, 16); break; case 'e': end = strtol(optarg, 0, 16); break; default: return 1; } } n = end + 1 - start; m = ROUNDUP(n, 16); present = _gc(malloc(m)); intotal = _gc(calloc(1, m)); if (optind < argc) { for (arg = optind; arg < argc; ++arg) { ttf = xslurp(argv[arg], &ttfsize); if (!(line = setjmp(stbtt_jmpbuf))) { stbtt_InitFont(&font, ttf, stbtt_GetFontOffsetForIndex(ttf, 0)); } else { rc = 1; fprintf(stderr, "%s: error loading font (assert @ stb_truetype.c:%d\n", argv[arg], line); free(ttf); continue; } bzero(present, m); for (maxcode = errs = 0, c = start; c <= end; ++c) { if (!(line = setjmp(stbtt_jmpbuf))) { if ((i = stbtt_FindGlyphIndex(&font, c)) > 0) { w = h = 0; scale = stbtt_ScaleForPixelHeight(&font, s); bitmap = stbtt_GetGlyphBitmap(&font, 0, scale, i, &w, &h, 0, 0); if (w && h) { intotal[c - start] = present[c - start] = 255; maxcode = c; } free(bitmap); } } else { ++errs; } } PrintBar(present, m); if (errs) { printf(" %s (%d errors)\n", basename(argv[arg]), errs); } else { printf(" %s (%,d kb)\n", basename(argv[arg]), ttfsize / 1024); } free(ttf); } PrintBar(intotal, m); fputc('\n', stdout); } return rc; }
4,915
134
jart/cosmopolitan
false
cosmopolitan/tool/viz/vdsodump.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/struct/sigaction.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/ucontext.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/sa.h" #include "libc/sysv/consts/sig.h" #include "third_party/xed/x86.h" #ifdef __x86_64__ #define OUTPATH "vdso.elf" volatile bool finished; void OnSegmentationFault(int sig, siginfo_t *si, void *vctx) { struct XedDecodedInst xedd; ucontext_t *ctx = vctx; xed_decoded_inst_zero_set_mode(&xedd, XED_MACHINE_MODE_LONG_64); xed_instruction_length_decode(&xedd, (void *)ctx->uc_mcontext.rip, 15); ctx->uc_mcontext.rip += xedd.length; finished = true; } int main(int argc, char *argv[]) { FILE *f; int byte; volatile unsigned char *vdso, *p; vdso = (unsigned char *)getauxval(AT_SYSINFO_EHDR); if (vdso) { fprintf(stderr, "vdso found at address %p\n", vdso); } else { fprintf(stderr, "error: AT_SYSINFO_EHDR was not in auxiliary values\n"); return 1; } f = fopen(OUTPATH, "wb"); if (!f) { fprintf(stderr, "error: fopen(%`'s) failed\n", OUTPATH); return 1; } struct sigaction sa = { .sa_sigaction = OnSegmentationFault, .sa_flags = SA_SIGINFO, }; sigaction(SIGSEGV, &sa, 0); sigaction(SIGBUS, &sa, 0); p = vdso; for (;;) { byte = *p++; if (!finished) { fputc(byte, f); } else { break; } } fclose(f); fprintf(stderr, "%zu bytes dumped to %s\n", p - vdso, OUTPATH); return 0; } #endif /* __x86_64__ */
3,393
86
jart/cosmopolitan
false
cosmopolitan/tool/viz/unbing.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/calls/calls.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" /** * @fileoverview UnBing: Glyphs → Binary. * * Intended for reassembling modified binaries. Characters that aren't * IBM CodePage 437 glyphs are ignored. That includes line feeds, so * it's safe to use the fold command on the bing program output, to have * something almost representing a source code file. A hack also exists * for comments in such files: 𝘶𝘴𝘦 𝑛𝑜𝑛-𝑎𝑠𝑐𝑖𝑖 𝗹𝗲𝘁𝘁𝗲𝗿𝗶𝗻𝗴 𝔞𝔩𝔱𝔢𝔯𝔫𝔞𝔱𝔦𝔳𝔢𝔰. * * bash$ o/tool/viz/bing.com </bin/sh | o/tool/viz/fold.com >sh.txt * bash$ emacs sh.txt * bash$ o/tool/viz/unbing.com <sh.txt >sh * bash$ chmod +x sh * bash$ ./sh * * That's how it works. */ uint16_t g_map[0x10000]; int main(int argc, char *argv[argc]) { size_t i; wint_t c; for (i = 0; i < 256; ++i) { g_map[kCp437[i]] = i + 1; } while ((c = fgetwc(stdin)) != WEOF) { if (c == (c & 0xffff) && g_map[c]) { fputc(g_map[c] - 1, stdout); } } return 0; }
2,965
57
jart/cosmopolitan
false
cosmopolitan/tool/viz/bd.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 "libc/stdio/stdio.h" /** * @fileoverview Braille Dump * * Written by Justine Tunney <[email protected]> * https://twitter.com/justinetunney * * Designed by Ange Albertini (corkami) * https://twitter.com/angealbertini * * See also `hexdump -C`. */ const wchar_t K[256] = L"▁☺☻♥♦♣♠•◘○◙♂♀♪♫☼" /* 0x00 */ L"►◄↕‼¶§▬↨↑↓→←∟↔▲▼" /* 0x10 */ L" !\"#$%&'()*+,-./" /* 0x20 */ L"0123456789:;<=>?" /* 0x30 */ L"@ABCDEFGHIJKLMNO" /* 0x40 */ L"PQRSTUVWXYZ[\\]^_" /* 0x50 */ L"`abcdefghijklmno" /* 0x60 */ L"pqrstuvwxyz{|}~⌂" /* 0x70 */ L"█⡀⢀⣀⠠⡠⢠⣠⠄⡄⢄⣄⠤⡤⢤⣤" /* 0x80 */ L"⠁⡁⢁⣁⠡⡡⢡⣡⠅⡅⢅⣅⠥⡥⢥⣥" /* 0x90 */ L"⠃⡃⢃⣃⠣⡣⢣⣣⠇⡇⢇⣇⠧⡧⢧⣧" /* 0xa0 */ L"⠉⡉⢉⣉⠩⡩⢩⣩⠍⡍⢍⣍⠭⡭⢭⣭" /* 0xb0 */ L"⠊⡊⢊⣊⠪⡪⢪⣪⠎⡎⢎⣎⠮⡮⢮⣮" /* 0xc0 */ L"⠑⡑⢑⣑⠱⡱⢱⣱⠕⡕⢕⣕⠵⡵⢵⣵" /* 0xd0 */ L"⠚⡚⢚⣚⠺⡺⢺⣺⠞⡞⢞⣞⠾⡾⢾⣾" /* 0xe0 */ L"⠛⡛⢛⣛⠻⡻⢻⣻⠟⡟⢟⣟⠿⡿⢿⣿"; /* 0xf0 */ int main(int argc, char *argv[]) { long o; FILE *f; int b, c, i, n; wchar_t B[17], *q; char R[16], A[50], *p; if (!(f = argc > 1 ? fopen(argv[1], "r") : stdin)) { fprintf(stderr, "ERROR: COULD NOT OPEN: %s\n", argv[1]); return 1; } for (b = o = 0;;) { if (!(n = fread(R, 1, 16, f))) break; p = A, q = B; for (c = i = 0; i < n; ++i) { if (i == 8) *p++ = ' '; *p++ = "0123456789abcdef"[(R[i] & 0xF0) >> 4]; *p++ = "0123456789abcdef"[(R[i] & 0x0F) >> 0]; *p++ = ' '; *q++ = K[R[i] & 255]; c |= R[i]; } if (c || !o) { *p = *q = b = 0; printf("%08x %-49s │%ls│\n", o, A, B); } else if (!b) { b = 1; printf("*\n"); } o += n; } if (o) printf("%08x\n", o); return !feof(f); }
4,100
83
jart/cosmopolitan
false
cosmopolitan/tool/viz/vdsosyms.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/elf/def.h" #include "libc/elf/scalar.h" #include "libc/elf/struct/ehdr.h" #include "libc/elf/struct/phdr.h" #include "libc/elf/struct/sym.h" #include "libc/elf/struct/verdaux.h" #include "libc/elf/struct/verdef.h" #include "libc/intrin/kprintf.h" #include "libc/intrin/strace.internal.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/auxv.h" static inline void PrintDsoSymbolVersions(Elf64_Verdef *vd, int sym, char *strtab) { Elf64_Verdaux *aux; for (;; vd = (Elf64_Verdef *)((char *)vd + vd->vd_next)) { if (!(vd->vd_flags & VER_FLG_BASE) && (vd->vd_ndx & 0x7fff) == (sym & 0x7fff)) { aux = (Elf64_Verdaux *)((char *)vd + vd->vd_aux); kprintf(" %s", strtab + aux->vda_name); } if (!vd->vd_next) { break; } } } int PrintVdsoSymbols(void) { void *p; size_t i; Elf64_Ehdr *ehdr; Elf64_Phdr *phdr; char *strtab = 0; size_t *dyn, base; unsigned long *ap; Elf64_Sym *symtab = 0; uint16_t *versym = 0; Elf_Symndx *hashtab = 0; Elf64_Verdef *verdef = 0; const char *typename, *bindname; for (ehdr = 0, ap = __auxv; ap[0]; ap += 2) { if (ap[0] == AT_SYSINFO_EHDR) { ehdr = (void *)ap[1]; break; } } if (!ehdr) { kprintf("error: AT_SYSINFO_EHDR not found\n"); return 1; } phdr = (void *)((char *)ehdr + ehdr->e_phoff); for (base = -1, dyn = 0, i = 0; i < ehdr->e_phnum; i++, phdr = (void *)((char *)phdr + ehdr->e_phentsize)) { switch (phdr->p_type) { case PT_LOAD: // modern linux uses the base address zero, but elders // e.g. rhel7 uses the base address 0xffffffffff700000 base = (size_t)ehdr + phdr->p_offset - phdr->p_vaddr; break; case PT_DYNAMIC: dyn = (void *)((char *)ehdr + phdr->p_offset); break; default: break; } } if (!dyn || base == -1) { kprintf("error: missing program headers\n"); return 2; } for (i = 0; dyn[i]; i += 2) { p = (void *)(base + dyn[i + 1]); switch (dyn[i]) { case DT_STRTAB: strtab = p; break; case DT_SYMTAB: symtab = p; break; case DT_HASH: hashtab = p; break; case DT_VERSYM: versym = p; break; case DT_VERDEF: verdef = p; break; } } if (!verdef) { versym = 0; } if (!strtab || !symtab || !hashtab) { kprintf("error: strtab/symtab/hashtab not found\n"); return 3; } for (i = 0; i < hashtab[1]; i++) { if (!symtab[i].st_shndx) { continue; } switch (ELF64_ST_BIND(symtab[i].st_info)) { case STB_LOCAL: bindname = "locl"; break; case STB_GLOBAL: bindname = "glob"; break; case STB_WEAK: bindname = "weak"; break; default: bindname = "????"; break; } switch (ELF64_ST_TYPE(symtab[i].st_info)) { case STT_FUNC: typename = "func"; break; case STT_OBJECT: typename = " obj"; break; case STT_NOTYPE: typename = "none"; break; default: typename = "????"; break; } kprintf("%s %s %-40s", bindname, typename, strtab + symtab[i].st_name); PrintDsoSymbolVersions(verdef, versym[i], strtab); kprintf("\n"); } return 0; } int main(int argc, char *argv[]) { return PrintVdsoSymbols(); }
5,306
167
jart/cosmopolitan
false
cosmopolitan/tool/viz/life.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 "dsp/scale/scale.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/termios.h" #include "libc/calls/struct/winsize.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/fmt/itoa.h" #include "libc/intrin/popcnt.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/xchg.internal.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/nt2sysv.h" #include "libc/nt/comdlg.h" #include "libc/nt/dll.h" #include "libc/nt/enum/bitblt.h" #include "libc/nt/enum/color.h" #include "libc/nt/enum/cw.h" #include "libc/nt/enum/idc.h" #include "libc/nt/enum/mb.h" #include "libc/nt/enum/mf.h" #include "libc/nt/enum/mk.h" #include "libc/nt/enum/ofn.h" #include "libc/nt/enum/rdw.h" #include "libc/nt/enum/sc.h" #include "libc/nt/enum/sw.h" #include "libc/nt/enum/wm.h" #include "libc/nt/enum/ws.h" #include "libc/nt/events.h" #include "libc/nt/messagebox.h" #include "libc/nt/paint.h" #include "libc/nt/struct/openfilename.h" #include "libc/nt/windows.h" #include "libc/runtime/runtime.h" #include "libc/sock/struct/pollfd.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/poll.h" #include "libc/sysv/consts/sig.h" #include "libc/sysv/consts/termios.h" #include "libc/time/time.h" #include "third_party/getopt/getopt.h" /** * @fileoverview Conway's Game of Life * * The Game of Life, also known simply as Life, is a cellular automaton * devised by the British mathematician John Horton Conway in 1970. It * is Turing complete and can simulate a universal constructor or any * other Turing machine. * * There's about 20 million Software Engineers in the world, which means * Game of Life has likely been implemented 20 million times before. Why * do we need this one? * * - It's a tutorial on how to build an Actually Portable Executable * that'll run as a GUI on Windows, and as a TUI on Linux/Mac/BSDs * using roughly one thousand lines of code. For a much better GUI * that's not as hackable, try Golly: http://golly.sourceforge.net * * - It's a tutorial on how to implement XTERM mouse cursor dragging * where zooming in/out can be performed too using ctrl+mousewheel * which is an underused (but easily implemented) terminal feature * that even the Windows10 Command Prompt supports these days. * * - It uses bitboards. That's almost as simple as the naive approach * but goes significantly faster, needing 150 picoseconds per board * position. See "Bitboard Methods for Games" by Cameron Browne for * further details on how it works. More advanced algorithms exist, * such as Hashlife: quadtree memoization to make humongous numbers * of generations tractable. * * Here's how you can compile this program on Linux: * * git clone https://github.com/jart/cosmopolitan && cd cosmopolitan * make -j12 o//tool/viz/life.com * * The output binary works on Linux, Windows, Mac, and FreeBSD: * * o//tool/viz/life.com * * @see https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life * @see https://www.conwaylife.com/wiki/Run_Length_Encoded * @see http://golly.sourceforge.net/ */ #define USAGE \ " [-zNW] [-w WIDTH] [-h HEIGHT] [PATH]\n\ \n\ DESCRIPTION\n\ \n\ Conway's Game of Life\n\ \n\ FLAGS\n\ \n\ -? help\n\ -z zoom\n\ -w INT board width\n\ -h INT board height\n\ -N natural scrolling\n\ -W white terminal background\n\ \n\ SHORTCUTS\n\ \n\ space step\n\ left+drag draw\n\ right+drag move\n\ ctrl+wheel zoom\n\ ctrl+t turbo\n\ alt+t slowmo\n\ R reset\n\ q quit\n\ \n" #define MAXZOOM 14 #define VOIDSPACE "." #define ALT (1 << 29) #define INTERRUPTED 1 #define RESIZED 2 #define IDM_ABOUT 0x10 #define IDM_OPEN 0x20 #define MOUSE_LEFT_DOWN 0 #define MOUSE_MIDDLE_DOWN 1 #define MOUSE_RIGHT_DOWN 2 #define MOUSE_LEFT_UP 4 #define MOUSE_MIDDLE_UP 5 #define MOUSE_RIGHT_UP 6 #define MOUSE_LEFT_DRAG 32 #define MOUSE_MIDDLE_DRAG 33 #define MOUSE_RIGHT_DRAG 34 #define MOUSE_WHEEL_UP 64 #define MOUSE_WHEEL_DOWN 65 #define MOUSE_CTRL_WHEEL_UP 80 #define MOUSE_CTRL_WHEEL_DOWN 81 struct Buffer { unsigned i, n; char *p; }; static bool erase; static bool white; static bool natural; static bool mousemode; static bool isdragging; static bool dimensioned; static int out; static int line; static int column; static int action; static int color[2]; static long top; static long bottom; static long left; static long right; static long tyn; static long txn; static long byn; static long bxn; static long zoom; static long speed; static long save_y; static long save_x; static long save_top; static long save_left; static long generation; static uint64_t *board; static uint64_t *board2; static size_t boardsize; static int64_t oldcursor; static struct Buffer buffer; static struct termios oldterm; static char name[64]; static char statusline[256]; static char16_t statusline16[256]; /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » algorithm ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ #define LEFT 0x0101010101010101ul #define RIGHT 0x8080808080808080ul #define TOP 0x00000000000000FFul #define BOTTOM 0xFF00000000000000ul #define CTRL(C) ((C) ^ 0100) #define GOUP(x) ((x) >> 8) #define GODOWN(x) ((x) << 8) #define GORIGHT(x) (((x) & ~RIGHT) << 1) #define GOLEFT(x) (((x) & ~LEFT) >> 1) #define LEFTMOST(x) ((x)&LEFT) #define RIGHTMOST(x) ((x)&RIGHT) #define TOPMOST(x) ((x)&TOP) #define BOTMOST(x) ((x)&BOTTOM) #define ADD(X) \ do { \ uint64_t c1, c2; \ c1 = r0 & (X); \ c2 = r1 & c1; \ r0 ^= (X); \ r1 ^= c1; \ r2 |= c2; \ } while (0) #define STEP(RES, B00, B01, B02, B10, B11, B12, B20, B21, B22) \ do { \ uint64_t r0 = 0, r1 = 0, r2 = 0; \ ADD(GORIGHT(GODOWN(B11)) | GORIGHT(BOTMOST(B01) >> 56) | \ GODOWN(RIGHTMOST(B10) >> 7) | BOTMOST(RIGHTMOST(B00)) >> 7 >> 56); \ ADD(GORIGHT(B11) | RIGHTMOST(B10) >> 7); \ ADD(GORIGHT(GOUP(B11)) | GORIGHT(TOPMOST(B21) << 56) | \ GOUP(RIGHTMOST(B10) >> 7) | TOPMOST(RIGHTMOST(B20)) >> 7 << 56); \ ADD(GODOWN(B11) | BOTMOST(B01) >> 56); \ ADD(GOUP(B11) | TOPMOST(B21) << 56); \ ADD(GOLEFT(GODOWN(B11)) | GOLEFT(BOTMOST(B01) >> 56) | \ GODOWN(LEFTMOST(B12) << 7) | BOTMOST(LEFTMOST(B02)) << 7 >> 56); \ ADD(GOLEFT(B11) | LEFTMOST(B12) << 7); \ ADD(GOLEFT(GOUP(B11)) | GOLEFT(TOPMOST(B21) << 56) | \ GOUP(LEFTMOST(B12) << 7) | TOPMOST(LEFTMOST(B22)) << 7 << 56); \ RES = (B11 | r0) & r1 & ~r2; \ } while (0) static void Step(void) { long y, x, yn, xn; yn = byn >> 3; xn = bxn >> 3; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { STEP(board2[y * xn + x], board[(y ? y - 1 : yn - 1) * xn + (x ? x - 1 : xn - 1)], board[(y ? y - 1 : yn - 1) * xn + x], board[(y ? y - 1 : yn - 1) * xn + (x + 1 < xn ? x + 1 : 0)], board[y * xn + (x ? x - 1 : xn - 1)], board[y * xn + x], board[y * xn + (x + 1 < xn ? x + 1 : 0)], board[(y + 1 < yn ? y + 1 : 0) * xn + (x ? x - 1 : xn - 1)], board[(y + 1 < yn ? y + 1 : 0) * xn + x], board[(y + 1 < yn ? y + 1 : 0) * xn + (x + 1 < xn ? x + 1 : 0)]); } } xchg(&board, &board2); ++generation; } static bool Test(long y, long x) { return (board[(bxn >> 3) * (y >> 3) + (x >> 3)] >> (((y & 7) << 3) + (x & 7))) & 1; } static void Set(long y, long x) { board[(bxn >> 3) * (y >> 3) + (x >> 3)] |= 1ul << (((y & 7) << 3) + (x & 7)); } static void Unset(long y, long x) { board[(bxn >> 3) * (y >> 3) + (x >> 3)] &= ~(1ul << (((y & 7) << 3) + (x & 7))); } static long Population(void) { return _countbits(board, byn * bxn / 64 * 8); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » buffer ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static void AppendData(char *data, unsigned len) { char *p; unsigned n; if (buffer.i + len + 1 > buffer.n) { n = MAX(buffer.i + len + 1, MAX(16, buffer.n + (buffer.n >> 1))); if (!(p = realloc(buffer.p, n))) return; buffer.p = p; buffer.n = n; } memcpy(buffer.p + buffer.i, data, len); buffer.p[buffer.i += len] = 0; } static void AppendChar(char c) { AppendData(&c, 1); } #define AppendStr(s) AppendData(s, strlen(s)) static void AppendInt(long x) { char ibuf[21]; AppendData(ibuf, FormatInt64(ibuf, x) - ibuf); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » board control ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static void Generation(void) { long i; for (i = 0; i < speed; ++i) { Step(); } } static void Dimension(void) { if (!dimensioned) { top = byn / 2 - tyn / 2; left = bxn / 2 - txn / 2; dimensioned = true; } right = left + txn; bottom = top + tyn; } static void Move(long dy, long dx) { long yn, xn; yn = zoom ? tyn * 2 : tyn; xn = txn; top = top + (dy << zoom); left = left + (dx << zoom); bottom = top + (yn << zoom); right = left + (xn << zoom); } static void OnUp(void) { Move(-1, 0); } static void OnDown(void) { Move(+1, 0); } static void OnLeft(void) { Move(0, -1); } static void OnRight(void) { Move(0, +1); } static void OnPageUp(void) { Move(-(tyn - 2), 0); } static void OnPageDown(void) { Move(+(tyn - 2), 0); } static void OnTurbo(void) { ++speed; } static void OnSlowmo(void) { --speed; if (speed < 1) speed = 1; } static void SetZoom(long y, long x, int d) { long a, b; if ((0 <= y && y < tyn) && (0 <= x && x < txn)) { a = zoom; b = MIN(MAXZOOM, MAX(0, a + d)); zoom = b; Move(((y << (a + !!a)) - (y << (b + !!b))) >> b, ((x << a) - (x << b)) >> b); } } static void OnZoom(long y, long x) { SetZoom(y, x, +1); } static void OnUnzoom(long y, long x) { SetZoom(y, x, -1); } static void OnMouseLeftDrag(long y, long x) { int i; if (y == save_y && x == save_x) return; save_y = y; save_x = x; y = top + (y << (zoom + !!zoom)); x = left + (x << zoom); y += _rand64() & ((1ul << (zoom + !!zoom)) - 1); x += _rand64() & ((1ul << zoom) - 1); if (y < 0 || y >= byn) return; if (x < 0 || x >= bxn) return; if (erase) { Unset(y, x); } else { for (i = 0; i < (2 << zoom); ++i) { Set(y + (rand() % (zoom + 1)) - (rand() % (zoom + 1)), x + (rand() % (zoom + 1)) - (rand() % (zoom + 1))); } } } static void OnMouseLeftUp(long y, long x) { isdragging = false; } static void OnMouseLeftDown(long y, long x) { isdragging = true; save_y = y; save_x = x; y = top + (y << (zoom + !!zoom)); x = left + (x << zoom); erase = false; if (y < 0 || y >= byn) return; if (x < 0 || x >= bxn) return; if ((erase = Test(y, x))) { Unset(y, x); } else { Set(y, x); } } static void OnMouseRightUp(long y, long x) { isdragging = false; } static void OnMouseRightDown(long y, long x) { isdragging = true; save_y = y; save_x = x; save_top = top; save_left = left; } static void OnMouseRightDrag(long y, long x) { long dy, dx, h, w; dy = (save_y - y) << zoom; dx = (save_x - x) << zoom; if (zoom) dy <<= 1; if (natural) { dy = -dy; dx = -dx; } h = bottom - top; w = right - left; top = save_top + dy; left = save_left + dx; bottom = top + h; right = left + w; } static void *NewBoard(size_t *out_size) { char *p; size_t s, n, k; s = (byn * bxn) >> 3; k = GUARDSIZE + ROUNDUP(s, GUARDSIZE); n = ROUNDUP(k + GUARDSIZE, FRAMESIZE); p = _mapanon(n); mprotect(p, GUARDSIZE, 0); mprotect(p + k, n - k, 0); if (out_size) *out_size = n; return p + GUARDSIZE; } static void FreeBoard(void *p, size_t n) { munmap((char *)p - GUARDSIZE, n); } static void AllocateBoardsWithHardwareAcceleratedMemorySafety(void) { if (board) { FreeBoard(board2, boardsize); FreeBoard(board, boardsize); } board = NewBoard(&boardsize); board2 = NewBoard(NULL); } static void GenerateStatusLine(void) { snprintf(statusline, sizeof(statusline), "%s :: %,ldg %,ldp %lds %ldx %ld×%ld (%ld,%ld,%ld,%ld)", name, generation, Population(), speed, zoom, byn, bxn, left, top, right, bottom); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » files ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static void OnHeader(void) { size_t n; if (!buffer.i) return; switch (buffer.p[0]) { case 'N': if (buffer.i > 2) { n = MIN(buffer.i - 2, sizeof(name) - 1); memcpy(name, buffer.p + 2, n); name[n] = 0; } break; default: break; } } static int ReadChar(FILE *f) { int c; ++column; if ((c = fgetc(f)) == -1) return -1; if (c == '\n') { ++line; column = 0; } return c; } static int GetChar(FILE *f) { int c; for (;;) { if ((c = ReadChar(f)) == -1) return -1; if (c == '#' && column == 1) { for (;;) { if ((c = ReadChar(f)) == -1) return -1; if (c == '\r') { continue; } else if (c == '\n') { OnHeader(); break; } AppendChar(c); } continue; } return c; } } static int LoadFile(const char *path) { FILE *f; long c, y, x, i, j, n, yn, xn, yo, xo; line = 0; f = fopen(path, "r"); if (GetChar(f) != 'x') goto ReadError; if (GetChar(f) != ' ') goto ReadError; if (GetChar(f) != '=') goto ReadError; if (GetChar(f) != ' ') goto ReadError; xn = 0; for (;;) { if ((c = GetChar(f)) == -1) goto ReadError; if (!isdigit(c)) break; xn *= 10; xn += c - '0'; } do { if ((c = GetChar(f)) == -1) goto ReadError; } while (!isdigit(c)); yn = 0; do { yn *= 10; yn += c - '0'; if ((c = GetChar(f)) == -1) goto ReadError; } while (isdigit(c)); while (c != '\n') { if ((c = ReadChar(f)) == -1) goto ReadError; } if (yn > byn || xn > bxn) goto ReadError; xchg(&board, &board2); bzero(board, (byn * bxn) >> 3); yo = byn / 2 - yn / 2; xo = bxn / 2 - xn / 2; y = 0; x = 0; for (;;) { if ((c = GetChar(f)) == -1) goto ReadError; if (c == '!') { break; } else if (isspace(c)) { continue; } if (isdigit(c)) { n = c - '0'; for (;;) { if ((c = GetChar(f)) == -1) goto ReadError; if (!isdigit(c)) break; n *= 10; n += c - '0'; } } else { n = 1; } if (c == '$') { if (++y == yn) y = 0; x = 0; } else if (c == 'b' || c == 'o') { for (i = 0; i < n; ++i) { if (x >= xn) { if (++y == yn) y = 0; x = 0; } if (c == 'o') { Set(yo + y, xo + x); } ++x; } } else { goto ReadError; } } fclose(f); dimensioned = false; return 0; ReadError: fclose(f); xchg(&board, &board2); return -1; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » terminal user interface ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static int Write(const char *s) { return write(out, s, strlen(s)); } static wontreturn void PrintUsage(int rc) { Write("SYNOPSIS\n\n "); Write(program_invocation_name); Write(USAGE); exit(rc); } static void GetOpts(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "?hNWzw:h:")) != -1) { switch (opt) { case 'w': bxn = strtol(optarg, NULL, 0); bxn = ROUNDUP(MAX(8, bxn), 8); break; case 'h': byn = strtol(optarg, NULL, 0); byn = ROUNDUP(MAX(8, byn), 8); break; case 'z': ++zoom; break; case 'N': natural = true; break; case 'W': white = true; break; case '?': PrintUsage(EXIT_SUCCESS); default: PrintUsage(EX_USAGE); } } } static void HideTtyCursor(void) { Write("\e[?25l"); } static void ShowTtyCursor(void) { Write("\e[?25h"); } static void EnableMouse(void) { mousemode = true; Write("\e[?1000;1002;1015;1006h"); } static void DisableMouse(void) { mousemode = false; Write("\e[?1000;1002;1015;1006l"); } static void LeaveScreen(void) { Write("\e[H\e[0m\e[J"); } static void GetTtySize(void) { struct winsize wsize; wsize.ws_row = tyn + 1; wsize.ws_col = txn; _getttysize(out, &wsize); tyn = wsize.ws_row - 1; txn = wsize.ws_col; right = left + txn; bottom = top + tyn; } static void EnableRaw(void) { struct termios term; memcpy(&term, &oldterm, sizeof(term)); term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 1; term.c_iflag &= ~(INPCK | ISTRIP | PARMRK | INLCR | IGNCR | ICRNL | IXON); term.c_lflag &= ~(IEXTEN | ICANON | ECHO | ECHONL); term.c_cflag &= ~(CSIZE | PARENB); term.c_cflag |= CS8; term.c_iflag |= IUTF8; ioctl(out, TCSETS, &term); } static void OnExit(void) { LeaveScreen(); ShowTtyCursor(); DisableMouse(); ioctl(out, TCSETS, &oldterm); } static void OnSigInt(int sig) { action |= INTERRUPTED; } static void OnSigWinch(int sig) { action |= RESIZED; } static void OnMouse(char *p) { int e, x, y; e = strtol(p, &p, 10); if (*p == ';') ++p; x = min(txn, max(1, strtol(p, &p, 10))) - 1; if (*p == ';') ++p; y = min(tyn, max(1, strtol(p, &p, 10))) - 1; e |= (*p == 'm') << 2; switch (e) { case MOUSE_WHEEL_UP: if (natural) { OnDown(); OnDown(); OnDown(); } else { OnUp(); OnUp(); OnUp(); } break; case MOUSE_WHEEL_DOWN: if (natural) { OnUp(); OnUp(); OnUp(); } else { OnDown(); OnDown(); OnDown(); } break; case MOUSE_CTRL_WHEEL_UP: if (natural) { OnZoom(y, x); } else { OnUnzoom(y, x); } break; case MOUSE_CTRL_WHEEL_DOWN: if (natural) { OnUnzoom(y, x); } else { OnZoom(y, x); } break; case MOUSE_RIGHT_DOWN: OnMouseRightDown(y, x); break; case MOUSE_RIGHT_DRAG: OnMouseRightDrag(y, x); break; case MOUSE_RIGHT_UP: OnMouseRightUp(y, x); break; case MOUSE_LEFT_DOWN: OnMouseLeftDown(y, x); break; case MOUSE_LEFT_DRAG: OnMouseLeftDrag(y, x); break; case MOUSE_LEFT_UP: OnMouseLeftUp(y, x); break; default: break; } } static void Rando1(void) { long i, n; n = (byn * bxn) >> 6; for (i = 0; i < n; ++i) { board[i] = _rand64(); } } static void Rando2(void) { long i, n; n = (byn * bxn) >> 6; for (i = 0; i < n; ++i) { board[i] = rand(); board[i] <<= 31; board[i] |= rand(); board[i] <<= 2; board[i] |= rand() & 0b11; } } static void ReadKeyboard(void) { char buf[32], *p = buf; bzero(buf, sizeof(buf)); if (readansi(0, buf, sizeof(buf)) == -1) { if (errno == EINTR) return; exit(errno); } switch (*p++) { case 'q': exit(0); case ' ': case 's': case '\t': Generation(); break; case 'k': case CTRL('P'): OnUp(); break; case 'j': case CTRL('N'): OnDown(); break; case CTRL('V'): OnPageDown(); break; case CTRL('R'): Rando1(); break; case CTRL('G'): Rando2(); break; case 'M': if (mousemode) { DisableMouse(); } else { EnableMouse(); } break; case 'R': bzero(board, (byn * bxn) >> 3); break; case CTRL('T'): OnTurbo(); break; case '\e': switch (*p++) { case 'v': OnPageUp(); break; case 't': OnSlowmo(); break; case '[': switch (*p++) { case '<': OnMouse(p); break; case 'A': OnUp(); break; case 'B': OnDown(); break; case 'D': OnLeft(); break; case 'C': OnRight(); break; case '5': switch (*p++) { case '~': OnPageUp(); break; default: break; } break; case '6': switch (*p++) { case '~': OnPageDown(); break; default: break; } break; default: break; } break; default: break; } break; default: break; } } static int InvertXtermGreyscale(int x) { return -(x - 232) + 255; } static int ByteToColor(int x) { uint8_t c; c = x / 256. * 24 + 232; if (white) c = InvertXtermGreyscale(c); return c; } static void SetColor(int x, bool isbg) { if (x != color[isbg]) { AppendStr("\e["); AppendInt(38 + 10 * isbg); AppendStr(";5;"); AppendInt(x); AppendStr("m"); color[isbg] = x; } } static void SetFg(int x) { SetColor(x, false); } static void SetBg(int x) { SetColor(x, true); } static void BitsToBytes(uint8_t a[8], uint64_t x) { a[0] = -((x >> 0) & 1); a[1] = -((x >> 1) & 1); a[2] = -((x >> 2) & 1); a[3] = -((x >> 3) & 1); a[4] = -((x >> 4) & 1); a[5] = -((x >> 5) & 1); a[6] = -((x >> 6) & 1); a[7] = -((x >> 7) & 1); } static void Raster(void) { long y, x; SetBg(ByteToColor(0)); SetFg(ByteToColor(255)); for (y = top; y < bottom; ++y) { for (x = left; x < right; ++x) { if ((0 <= y && y < byn) && (0 <= x && x < bxn)) { if (Test(y, x)) { AppendStr("█"); } else { AppendStr(" "); } } else { AppendStr(VOIDSPACE); } } } } static void RasterZoomed(long t, long l, long b, long r, uint8_t p[b - t][r - l]) { uint64_t c; uint8_t b1, b2; long i, y, x, yn, xn; for (y = MAX(0, t); y < MIN(b, byn); y += 8) { for (x = MAX(0, l); x < MIN(r, bxn); x += 8) { c = board[(bxn >> 3) * (y >> 3) + (x >> 3)]; for (i = 0; i < 8; ++i) { BitsToBytes(&p[y - t + i][x - l], c); c >>= 8; } } } yn = b - t; xn = r - l; for (i = 0; i < zoom; ++i) { Magikarp2xX(b - t, r - l, p, yn, xn); Magikarp2xY(b - t, r - l, p, yn, xn); yn >>= 1; xn >>= 1; } for (y = top; y < bottom; y += 2ul << zoom) { for (x = left; x < right; x += 1ul << zoom) { if ((0 <= y && y < byn) && (0 <= x && x < bxn)) { b1 = p[((top - t) + ((y + 0) - top)) >> zoom] [((left - l) + (x - left)) >> zoom]; b2 = y + (1ul << zoom) < bottom ? p[((top - t) + ((y + 1) - top)) >> zoom] [((left - l) + (x - left)) >> zoom] : 0; if (b1 || b2) { SetBg(ByteToColor(b1)); SetFg(ByteToColor(b2)); AppendStr("▄"); } else { SetBg(ByteToColor(0)); SetFg(ByteToColor(255)); AppendStr(" "); } } else { SetBg(ByteToColor(0)); SetFg(ByteToColor(255)); AppendStr(VOIDSPACE); } } } } static void Draw(void) { void *m; long t, l, b, r, i, n; buffer.i = 0; color[0] = -1; color[1] = -1; AppendStr("\e[H"); if (!zoom) { Raster(); } else { t = ROUNDDOWN(top, 16); l = ROUNDDOWN(left, 16); b = ROUNDUP(bottom, 16); r = ROUNDUP(right, 16); if ((m = calloc((b - t) * (r - l), 1))) { RasterZoomed(t, l, b, r, m); free(m); } } AppendStr("\e[0;7m"); GenerateStatusLine(); AppendStr(statusline); n = txn - strwidth(statusline, 0); for (i = 0; i < n; ++i) { AppendStr(" "); } AppendStr("\e[0m"); write(out, buffer.p, buffer.i); } static bool HasPendingInput(void) { struct pollfd fds[1]; fds[0].fd = 0; fds[0].events = POLLIN; fds[0].revents = 0; poll(fds, ARRAYLEN(fds), 0); return fds[0].revents & (POLLIN | POLLERR); } static bool ShouldDraw(void) { long double now, rate; static long double next; if (!isdragging) return true; now = nowl(); rate = 1. / 24; if (now > next && !HasPendingInput()) { next = now + rate; return true; } else { return false; } } static void Tui(void) { GetTtySize(); Dimension(); ioctl(out, TCGETS, &oldterm); HideTtyCursor(); EnableRaw(); EnableMouse(); atexit(OnExit); sigaction(SIGINT, &(struct sigaction){.sa_handler = OnSigInt}, 0); sigaction(SIGWINCH, &(struct sigaction){.sa_handler = OnSigWinch}, 0); do { if (action & RESIZED) { GetTtySize(); action &= ~RESIZED; Draw(); } else if (ShouldDraw()) { Draw(); } ReadKeyboard(); } while (!(action & INTERRUPTED)); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » graphical user interface ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static const char16_t kClassName[] = u"apelife"; static void OnMenuAbout(int64_t hwnd) { MessageBox(hwnd, u"\ Apelife\r\n\ Cosmopolitan C Library\r\n\ αcτµαlly pδrταblε εxεcµταblε\r\n\ By Justine Tunney <[email protected]>\r\n\ In memory of John Horton Conway, 1937-2020\r\n\ https://github.com/jart/cosmopolitan\r\n\ \r\n\ - Hold space to animate\r\n\ - Hold left mouse to draw cells\r\n\ - Hold right mouse to move view\r\n\ - Press t or alt+t to adjust speed", u"Conway's Game of Life", kNtMbOk | kNtMbIconinformation); } static void OnMenuOpen(int64_t hwnd) { char buf8[PATH_MAX]; char16_t buf16[PATH_MAX]; struct NtOpenFilename ofn; bzero(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwnd; ofn.lpstrFile = buf16; ofn.nMaxFile = ARRAYLEN(buf16); ofn.lpstrFilter = u"RLE Format (*.RLE;*.LIF;*.LIFE)\0" u"*.RLE;*.LIF;*.LIFE\0" u"All (*.*)\0" u"*.*\0"; ofn.Flags = kNtOfnPathmustexist | kNtOfnFilemustexist | kNtOfnExplorer; if (GetOpenFileName(&ofn)) { tprecode16to8(buf8, sizeof(buf8), ofn.lpstrFile); if (LoadFile(buf8) == -1) { MessageBox(hwnd, u"Failed to open run-length encoded game file", u"Open Failed", kNtMbOk | kNtMbIconerror); } RedrawWindow(hwnd, 0, 0, kNtRdwInvalidate); } } static bool IsMaximized(int64_t hwnd) { struct NtWindowPlacement wp; wp.length = sizeof(wp); return GetWindowPlacement(hwnd, &wp) && wp.showCmd == kNtSwMaximize; } static void OnWindowPaint(int64_t hwnd) { int y, x; int64_t mdc, mbm; struct NtRect r, w; struct NtPaintStruct ps; BeginPaint(hwnd, &ps); r.top = 0; r.left = 0; r.right = ps.rcPaint.right - ps.rcPaint.left; r.bottom = ps.rcPaint.bottom - ps.rcPaint.top; w.top = MAX(r.top, -(top + ps.rcPaint.top)); w.left = MAX(r.left, -(left + ps.rcPaint.left)); w.right = MIN(r.right, bxn - (left + ps.rcPaint.left)); w.bottom = MIN(r.bottom, byn - (top + ps.rcPaint.top)); mdc = CreateCompatibleDC(ps.hdc); mbm = CreateCompatibleBitmap(ps.hdc, r.right, r.bottom); SelectObject(mdc, mbm); FillRect(mdc, &r, kNtColorInactiveborder); FillRect(mdc, &w, kNtColorAppworkspace); for (y = w.top; y < w.bottom; ++y) { for (x = w.left; x < w.right; ++x) { if (Test(top + ps.rcPaint.top + y, left + ps.rcPaint.left + x)) { SetPixel(mdc, x, y, 0); } } } BitBlt(ps.hdc, ps.rcPaint.left, ps.rcPaint.top, r.right, r.bottom, mdc, 0, 0, kNtSrccopy); DeleteObject(mbm); DeleteDC(mdc); GenerateStatusLine(); tprecode8to16(statusline16, ARRAYLEN(statusline16), statusline); SetWindowText(hwnd, statusline16); EndPaint(hwnd, &ps); } static void OnWindowCharStep(int64_t hwnd, int64_t wParam, int64_t lParam) { int i, repeats; repeats = lParam & 0xFFFF; for (i = 0; i < repeats; ++i) { Generation(); } RedrawWindow(hwnd, 0, 0, kNtRdwInvalidate); } static void OnWindowChar(int64_t hwnd, int64_t wParam, int64_t lParam) { switch (wParam) { case ' ': case 's': case '\t': OnWindowCharStep(hwnd, wParam, lParam); break; case 't': if (lParam & ALT) { OnSlowmo(); } else { OnTurbo(); } break; case '\r': if (IsMaximized(hwnd)) { SendMessage(hwnd, kNtWmSyscommand, kNtScRestore, 0); } else { SendMessage(hwnd, kNtWmSyscommand, kNtScMaximize, 0); } break; default: break; } } static void OnWindowSize(int64_t lParam) { txn = (lParam & 0x0000FFFF) >> 000; tyn = (lParam & 0xFFFF0000) >> 020; Dimension(); } static void OnWindowLbuttondown(int64_t hwnd, int64_t wParam, int64_t lParam) { int y, x; y = (lParam & 0xFFFF0000) >> 020; x = (lParam & 0x0000FFFF) >> 000; SetCapture(hwnd); OnMouseLeftDown(y, x); RedrawWindow(hwnd, &(struct NtRect){x, y, x + 1, y + 1}, 0, kNtRdwInvalidate); } static void OnWindowLbuttonup(int64_t hwnd, int64_t wParam, int64_t lParam) { int y, x; y = (lParam & 0xFFFF0000) >> 020; x = (lParam & 0x0000FFFF) >> 000; OnMouseLeftUp(y, x); ReleaseCapture(); } static void OnWindowRbuttondown(int64_t hwnd, int64_t wParam, int64_t lParam) { int y, x; y = (lParam & 0xFFFF0000) >> 020; x = (lParam & 0x0000FFFF) >> 000; oldcursor = GetCursor(); SetCapture(hwnd); SetCursor(LoadCursor(0, kNtIdcSizeall)); OnMouseRightDown(y, x); RedrawWindow(hwnd, NULL, 0, kNtRdwInvalidate); } static void OnWindowRbuttonup(int64_t hwnd, int64_t wParam, int64_t lParam) { int y, x; y = (lParam & 0xFFFF0000) >> 020; x = (lParam & 0x0000FFFF) >> 000; OnMouseRightUp(y, x); SetCursor(oldcursor); ReleaseCapture(); } static void OnWindowMousemove(int64_t hwnd, int64_t wParam, int64_t lParam) { int y, x, by, bx; y = (lParam & 0xFFFF0000) >> 020; x = (lParam & 0x0000FFFF) >> 000; if (wParam & kNtMkLbutton) { OnMouseLeftDrag(y, x); RedrawWindow(hwnd, &(struct NtRect){x, y, x + 1, y + 1}, 0, kNtRdwInvalidate); } else if (wParam & kNtMkRbutton) { OnMouseRightDrag(y, x); RedrawWindow(hwnd, NULL, 0, kNtRdwInvalidate); } } static int64_t WindowProc(int64_t hwnd, uint32_t uMsg, uint64_t wParam, int64_t lParam) { switch (uMsg) { case kNtWmDestroy: PostQuitMessage(0); return 0; case kNtWmSize: OnWindowSize(lParam); return 0; case kNtWmPaint: OnWindowPaint(hwnd); return 0; case kNtWmChar: OnWindowChar(hwnd, wParam, lParam); return 0; case kNtWmLbuttondown: OnWindowLbuttondown(hwnd, wParam, lParam); return 0; case kNtWmLbuttonup: OnWindowLbuttonup(hwnd, wParam, lParam); return 0; case kNtWmRbuttondown: OnWindowRbuttondown(hwnd, wParam, lParam); return 0; case kNtWmRbuttonup: OnWindowRbuttonup(hwnd, wParam, lParam); return 0; case kNtWmMousemove: OnWindowMousemove(hwnd, wParam, lParam); return 0; case kNtWmCommand: case kNtWmSyscommand: switch (wParam & ~0xF) { case IDM_ABOUT: OnMenuAbout(hwnd); return 0; case IDM_OPEN: OnMenuOpen(hwnd); return 0; } /* fallthrough */ default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } } static void Gui(void) { int64_t hwnd, mh; struct NtMsg msg; struct NtWndClass wc; bzero(&wc, sizeof(wc)); wc.lpfnWndProc = NT2SYSV(WindowProc); wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(0, kNtIdcCross); wc.lpszClassName = kClassName; wc.hbrBackground = kNtColorInactiveborder; CHECK(RegisterClass(&wc)); CHECK((hwnd = CreateWindowEx(0, kClassName, u"Conway's Game of Life", kNtWsOverlappedwindow, kNtCwUsedefault, kNtCwUsedefault, kNtCwUsedefault, kNtCwUsedefault, 0, 0, wc.hInstance, 0))); mh = GetSystemMenu(hwnd, false); AppendMenu(mh, kNtMfSeparator, 0, 0); AppendMenu(mh, kNtMfEnabled, IDM_OPEN, u"&Open File..."); AppendMenu(mh, kNtMfEnabled, IDM_ABOUT, u"&About..."); ShowWindow(hwnd, kNtSwNormal); while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } /*───────────────────────────────────────────────────────────────────────────│─╗ │ cosmopolitan § game of life » program ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ int main(int argc, char *argv[]) { if (!NoDebug()) ShowCrashReports(); out = 1; speed = 1; tyn = right = 80; txn = bottom = 24; byn = 64 * 64; bxn = 64 * 64; strcpy(name, "apelife"); GetOpts(argc, argv); AllocateBoardsWithHardwareAcceleratedMemorySafety(); if (optind < argc) { if (LoadFile(argv[optind]) == -1) { fprintf( stderr, "%s:%d:%d: %s\n", argv[optind], line + 1, column, "error: failed to load game of life run length encoded (rle) file"); return 1; } } if (IsWindows()) { Gui(); } else { Tui(); } return 0; }
38,769
1,405
jart/cosmopolitan
false
cosmopolitan/tool/viz/printimage.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 "dsp/core/half.h" #include "dsp/core/twixt8.h" #include "dsp/scale/scale.h" #include "dsp/tty/quant.h" #include "dsp/tty/tty.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/winsize.h" #include "libc/dce.h" #include "libc/fmt/conv.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/termios.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image.h" #include "tool/viz/lib/graphic.h" STATIC_YOINK("__zipos_get"); static struct Flags { const char *out; bool subpixel; bool unsharp; bool dither; bool ruler; bool magikarp; long half; bool full; bool ignoreaspect; long width; long height; enum TtyBlocksSelection blocks; enum TtyQuantizationAlgorithm quant; } g_flags; struct winsize g_winsize; static wontreturn void PrintUsage(int rc, FILE *f) { fprintf(f, "Usage: %s%s", program_invocation_name, "\ [FLAGS] [PATH]\n\ \n\ FLAGS\n\ \n\ -o PATH output path\n\ -w INT manual width\n\ -h INT manual height\n\ -f display full size\n\ -i ignore aspect ratio\n\ -4 unicode blocks\n\ -a ansi color mode\n\ -t true color mode\n\ -2 use half blocks\n\ -3 ibm cp437 blocks\n\ -s unsharp sharpening\n\ -x xterm256 color mode\n\ -m use magikarp scaling\n\ -d hilbert curve dithering\n\ -r display pixel ruler on sides\n\ -p convert to subpixel layout\n\ -v increases verbosity\n\ -? shows this information\n\ \n\ EXAMPLES\n\ \n\ printimage.com -sxd lemurs.jpg # 256-color dither unsharp\n\ \n"); exit(rc); } static int ParseNumberOption(const char *arg) { long x; x = strtol(arg, NULL, 0); if (!(1 <= x && x <= INT_MAX)) { fprintf(stderr, "invalid flexidecimal: %s\n\n", arg); exit(EXIT_FAILURE); } return x; } static void GetOpts(int *argc, char *argv[]) { int opt; g_flags.quant = kTtyQuantTrue; g_flags.blocks = IsWindows() ? kTtyBlocksCp437 : kTtyBlocksUnicode; if (*argc == 2 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-help") == 0)) { PrintUsage(EXIT_SUCCESS, stdout); } while ((opt = getopt(*argc, argv, "?vpmfirtxads234o:w:h:")) != -1) { switch (opt) { case 'o': g_flags.out = optarg; break; case 'd': g_flags.dither = true; break; case 's': g_flags.unsharp = true; break; case 'w': g_flags.width = ParseNumberOption(optarg); break; case 'h': g_flags.height = ParseNumberOption(optarg); break; case 'f': g_flags.full = true; break; case 'i': g_flags.ignoreaspect = true; break; case '2': g_flags.half = true; break; case 'r': g_flags.ruler = true; break; case 'm': g_flags.magikarp = true; break; case 'p': g_flags.subpixel = true; break; case 'a': g_flags.quant = kTtyQuantAnsi; break; case 'x': g_flags.quant = kTtyQuantXterm256; break; case 't': g_flags.quant = kTtyQuantTrue; break; case '3': g_flags.blocks = kTtyBlocksCp437; break; case '4': g_flags.blocks = kTtyBlocksUnicode; break; case 'v': ++__log_level; break; case '?': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } g_winsize.ws_col = 80; g_winsize.ws_row = 24; if (!g_flags.full && (!g_flags.width || !g_flags.height)) { ioctl(STDIN_FILENO, TIOCGWINSZ, &g_winsize) != -1 || ioctl(STDOUT_FILENO, TIOCGWINSZ, &g_winsize); } ttyquantsetup(g_flags.quant, kTtyQuantRgb, g_flags.blocks); } static unsigned char ChessBoard(unsigned y, unsigned x, unsigned char a, unsigned char b) { return !((y ^ x) & (1u << 2)) ? a : b; } static unsigned char AlphaBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 255, 200); } static unsigned char OutOfBoundsBackground(unsigned y, unsigned x) { return ChessBoard(y, x, 40, 80); } static void PrintRulerRight(long yn, long xn, long y, long x, bool *inout_didhalfy) { if (y == 0) { printf("‾0"); } else if (yn / 2 <= y && y <= yn / 2 + 1 && !*inout_didhalfy) { printf("‾%s%s", "yn/2", y % 2 ? "+1" : ""); *inout_didhalfy = true; } else if (y + 1 == yn / 2 && !*inout_didhalfy) { printf("⎯yn/2"); *inout_didhalfy = true; } else if (y + 1 == yn) { printf("⎯yn"); } else if (y + 2 == yn) { printf("_yn"); } else if (!(y % 10)) { printf("‾%,u", y); } } static void PrintImageImpl(long syn, long sxn, unsigned char RGB[3][syn][sxn], long y0, long yn, long x0, long xn, long dy, long dx) { long y, x; bool didhalfy, didfirstx; unsigned char a[3], b[3]; didhalfy = false; for (y = y0; y < yn; y += dy) { didfirstx = false; if (y) printf("\e[0m\n"); for (x = x0; x < xn; x += dx) { a[0] = RGB[0][y][x]; a[1] = RGB[1][y][x]; a[2] = RGB[2][y][x]; if (y + dy < yn && x + dx < xn) { b[0] = RGB[0][y + dy][x + dx]; b[1] = RGB[1][y + dy][x + dx]; b[2] = RGB[2][y + dy][x + dx]; } else { b[2] = b[1] = b[0] = OutOfBoundsBackground(y + dy, x + dx); } printf("\e[48;2;%d;%d;%d;38;2;%d;%d;%dm%lc", a[0], a[1], a[2], b[0], b[1], b[2], dy > 1 ? u'▄' : u'▐'); didfirstx = true; } printf("\e[0m"); if (g_flags.ruler) { PrintRulerRight(yn, xn, y, x, &didhalfy); } } printf("\n"); } static void PrintImage(long syn, long sxn, unsigned char RGB[3][syn][sxn], long y0, long yn, long x0, long xn) { PrintImageImpl(syn, sxn, RGB, y0, yn, x0, xn, 2, 1); } static void PrintImageLR(long syn, long sxn, unsigned char RGB[3][syn][sxn], long y0, long yn, long x0, long xn) { PrintImageImpl(syn, sxn, RGB, y0, yn, x0, xn, 1, 2); } static void *Deblinterlace(long dyn, long dxn, unsigned char dst[3][dyn][dxn], long syn, long sxn, long scn, const unsigned char src[syn][sxn][scn], long y0, long yn, long x0, long xn) { long y, x; unsigned char c; for (y = y0; y < yn; ++y) { for (x = x0; x < xn; ++x) { switch (scn) { case 1: c = src[y][x][0]; dst[0][y][x] = c; dst[1][y][x] = c; dst[2][y][x] = c; break; case 2: c = twixt8(AlphaBackground(y, x), src[y][x][0], src[y][x][1]); dst[0][y][x] = c; dst[1][y][x] = c; dst[2][y][x] = c; break; case 3: dst[0][y][x] = src[y][x][0]; dst[1][y][x] = src[y][x][1]; dst[2][y][x] = src[y][x][2]; break; case 4: c = AlphaBackground(y, x); dst[0][y][x] = twixt8(c, src[y][x][0], src[y][x][3]); dst[1][y][x] = twixt8(c, src[y][x][1], src[y][x][3]); dst[2][y][x] = twixt8(c, src[y][x][2], src[y][x][3]); break; } } } return dst; } static void *DeblinterlaceSubpixelBgr(long dyn, long dxn, unsigned char dst[3][dyn][dxn][3], long syn, long sxn, const unsigned char src[syn][sxn][4], long y0, long yn, long x0, long xn) { long y, x; for (y = y0; y < yn; ++y) { for (x = x0; x < xn; ++x) { dst[0][y][x][0] = 0; dst[1][y][x][0] = 0; dst[2][y][x][0] = src[y][x][2]; dst[0][y][x][1] = 0; dst[1][y][x][1] = src[y][x][1]; dst[2][y][x][1] = 0; dst[0][y][x][2] = src[y][x][0]; dst[1][y][x][2] = 0; dst[2][y][x][2] = 0; } } return dst; } static void PrintImageSerious(long yn, long xn, unsigned char RGB[3][yn][xn], long tyn, long txn, struct TtyRgb TTY[tyn][txn], char *vt) { char *p; long y, x; struct TtyRgb bg = {0x12, 0x34, 0x56, 0}; struct TtyRgb fg = {0x12, 0x34, 0x56, 0}; if (g_flags.unsharp) unsharp(3, yn, xn, RGB, yn, xn); if (g_flags.dither) dither(yn, xn, RGB, yn, xn); if (yn && xn) { for (y = 0; y < tyn; ++y) { for (x = 0; x < txn; ++x) { TTY[y][x] = rgb2tty(RGB[0][MIN(y, yn - 1)][MIN(x, xn - 1)], RGB[1][MIN(y, yn - 1)][MIN(x, xn - 1)], RGB[2][MIN(y, yn - 1)][MIN(x, xn - 1)]); } } } p = ttyraster(vt, (void *)TTY, tyn, txn, bg, fg); p = stpcpy(p, "\e[0m\r\n"); ttywrite(STDOUT_FILENO, vt, p - vt); } static void ProcessImage(long yn, long xn, unsigned char RGB[3][yn][xn]) { long tyn, txn; if (g_flags.half) { if (g_flags.subpixel) { PrintImageLR(yn, xn * 3, RGB, 0, yn, 0, xn * 3); } else { PrintImage(yn, xn, RGB, 0, yn, 0, xn); } } else { tyn = ROUNDUP(yn, 2); txn = ROUNDUP(xn, 2); PrintImageSerious( yn, xn, RGB, tyn, txn, gc(calloc(sizeof(struct TtyRgb), tyn * txn)), gc(calloc(1, ((yn * xn * strlen("\e[48;2;255;48;2;255m▄")) + (yn * strlen("\e[0m\r\n")) + 128)))); } } void WithImageFile(const char *path, void fn(long yn, long xn, unsigned char RGB[3][yn][xn])) { struct stat st; void *map, *data, *data2; int fd, yn, xn, cn, dyn, dxn, syn, sxn, wyn, wxn; CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_GT(st.st_size, 0); CHECK_LE(st.st_size, INT_MAX); fadvise(fd, 0, st.st_size, MADV_WILLNEED | MADV_SEQUENTIAL); CHECK_NE(MAP_FAILED, (map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))); CHECK_NOTNULL( (data = gc(stbi_load_from_memory(map, st.st_size, &xn, &yn, &cn, 0))), "%s", path); CHECK_NE(-1, munmap(map, st.st_size)); CHECK_NE(-1, close(fd)); if (g_flags.subpixel) { data = DeblinterlaceSubpixelBgr(yn, xn, gc(memalign(32, yn * xn * 4 * 3)), yn, xn, data, 0, yn, 0, xn); xn *= 3; } else { data = Deblinterlace(yn, xn, gc(memalign(32, yn * xn * 4)), yn, xn, cn, data, 0, yn, 0, xn); cn = 3; } if (!g_flags.full) { syn = yn; sxn = xn; dyn = g_flags.height; dxn = g_flags.width; wyn = g_winsize.ws_row * 2; wxn = g_winsize.ws_col; if (g_flags.ignoreaspect) { if (!dyn) dyn = wyn; if (!dxn) dxn = wxn * (1 + !g_flags.half); } if (!dyn && !dxn) { if (sxn * wyn > syn * wxn) { dxn = wxn * (1 + !g_flags.half); } else { dyn = wyn; } } if (dyn && !dxn) { dxn = dyn * sxn * (1 + !g_flags.half) / syn; } else if (dxn && !dyn) { dyn = dxn * syn / (sxn * (1 + !g_flags.half)); } if (g_flags.magikarp) { while (HALF(syn) > dyn || HALF(sxn) > dxn) { if (HALF(sxn) > dxn) { Magikarp2xX(yn, xn, data, syn, sxn); Magikarp2xX(yn, xn, (char *)data + yn * xn, syn, sxn); Magikarp2xX(yn, xn, (char *)data + yn * xn * 2, syn, sxn); sxn = HALF(sxn); } if (HALF(syn) > dyn) { Magikarp2xY(yn, xn, data, syn, sxn); Magikarp2xY(yn, xn, (char *)data + yn * xn, syn, sxn); Magikarp2xY(yn, xn, (char *)data + yn * xn * 2, syn, sxn); syn = HALF(syn); } } } data = EzGyarados(3, dyn, dxn, gc(memalign(32, dyn * dxn * 3)), cn, yn, xn, data, 0, cn, dyn, dxn, syn, sxn, 0, 0, 0, 0); yn = dyn; xn = dxn; } fn(yn, xn, data); } int main(int argc, char *argv[]) { int i; ShowCrashReports(); GetOpts(&argc, argv); if (optind == argc) PrintUsage(0, stdout); stbi_set_unpremultiply_on_load(true); for (i = optind; i < argc; ++i) { WithImageFile(argv[i], ProcessImage); } return 0; }
14,424
446
jart/cosmopolitan
false
cosmopolitan/tool/viz/ascii2utf8.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/errno.h" #include "libc/stdio/stdio.h" /** @fileoverview Converts ASCII combining marks to UNICODE. Getting started: nroff -mandoc -rLL=72n -rLT=78n -Tutf8 <manpage.1 | o/tool/viz/ascii2utf8.com ASCII Bold: - CHAR BACKSPACE CHAR c ++ "\b" ++ c e.g. AABBCCDD 410841 420842 430843 440844 ASCII Underlines: - CHAR BACKSPACE LOW LINE c ++ "\b_" e.g. A_B_C_D_ 41085F 42085F 43085F 44085F UNICODE Underlines: - COMBINING LOW LINE U+0332 (\xCC\xB1) e.g. A̲B̲C̲D̲ (ugly notches) 41CCB2 42CCB2 43CCB2 44CCB2 - COMBINING MACRON BELOW U+0331 (\xCC\xB1) e.g. A̱ḆC̱Ḏ (too short) 41CCB1 42CCB1 43CCB1 44CCB1 - COMBINING DOUBLE MACRON BELOW U+035F (\xCD\x9F) e.g. A͟B͟C͟D͟ (too long) 41CD9F 42CD9F 43CD9F 44CD9F - DOUBLE PLUS COMBINING MACRON BELOW 3×U+035F + 1×U+0331 e.g. A͟B͟C͟Ḏ (too narrow) 41CCB1 42CCB1 43CCB1 44CD9F - DOUBLE PLUS COMBINING MACRON LOW LINE [it's complicated] e.g. A͟B͟C͟D̲ (𝑓𝑙𝑎𝑤𝑙𝑒𝑠𝑠) 41CD9F 42CD9F 43CD9F 44CCB2 */ const wint_t kBackspace = '\b'; const wint_t kCombiningLowLine = L'\u0332'; const wint_t kCombiningDoubleMacronBelow = L'\u035f'; forceinline int PutChar(wint_t (*buf)[3], size_t *i, wint_t *cc, FILE *out) { if (fputwc((*buf)[0], out) == -1) return -1; if (*cc != -1) { if (fputwc(*cc, out) == -1) return -1; *cc = -1; } (*buf)[0] = (*buf)[1]; (*buf)[1] = (*buf)[2]; --*i; return 0; } int CombineAsciiMarks(FILE *in, FILE *out) { wint_t buf[3], wc = 0, cc = -1; size_t i = 0; for (;;) { while (i < 3) { if ((wc = fgetwc(in)) == -1) goto InputBreak; buf[i++] = wc; } if (buf[1] == '\b' && cc == -1) { if (buf[0] == buf[2]) { /* bold */ if (L'0' <= buf[0] && buf[0] <= L'9') { buf[0] = L'𝟬' + (buf[0] - L'0'); i = 1; } else if (L'A' <= buf[0] && buf[0] <= L'Z') { buf[0] = L'𝐀' + (buf[0] - L'A'); i = 1; } else if ('a' <= buf[0] && buf[0] <= L'z') { buf[0] = L'𝗮' + (buf[0] - L'a'); i = 1; } else { i = 1; } } else if (buf[2] == '_') { /* underline */ cc = kCombiningLowLine; i = 1; } else if (buf[0] == '_') { cc = kCombiningLowLine; buf[0] = buf[2]; i = 1; } } if (i == 3) { if (PutChar(&buf, &i, &cc, out) == -1) goto OutputBreak; } } InputBreak: while (i) { if (PutChar(&buf, &i, &cc, out) == -1) goto OutputBreak; } OutputBreak: return (fclose(in) | fclose(out)) != -1 ? 0 : -1; } int main(int argc, char *argv[]) { return CombineAsciiMarks(stdin, stdout) != -1 ? 0 : errno; }
4,815
121
jart/cosmopolitan
false
cosmopolitan/tool/viz/deathstar.c
#include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/calls/struct/termios.h" #include "libc/intrin/safemacros.internal.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/sig.h" #include "third_party/libcxx/math.h" /** * @fileoverview demo code borrowed from Rosetta Code. */ #define FRAMERATE 23.976 #define WRITE(s) write(1, s, strlen(s)) struct Sphere { double cx, cy, cz, r; }; static const char *kShades[] = { "\e[48;5;232m ", "\e[48;5;233m ", "\e[48;5;234m ", "\e[48;5;235m ", "\e[48;5;236m ", "\e[48;5;237m ", "\e[48;5;238m ", "\e[48;5;239m ", "\e[48;5;240m ", "\e[48;5;241m ", "\e[48;5;242m ", "\e[48;5;243m ", "\e[48;5;244m ", "\e[48;5;245m ", "\e[48;5;246m ", "\e[48;5;247m ", "\e[48;5;248m ", "\e[48;5;249m ", "\e[48;5;250m ", "\e[48;5;251m ", "\e[48;5;252m ", "\e[48;5;253m ", "\e[48;5;254m ", "\e[48;5;255m ", }; static jmp_buf jb_; static double light_[3] = {-50, 0, 50}; static struct Sphere pos_ = {11, 11, 11, 11}; static struct Sphere neg_ = {1, 1, -4, 11}; static void OnCtrlC(int sig) { longjmp(jb_, 1); } static void Normalize(double v[3]) { double len; len = 1 / sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] *= len; v[1] *= len; v[2] *= len; } static double Dot(const double x[3], const double y[3]) { return fabs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]); } /* check if a ray (x,y, -inf)->(x, y, inf) hits a sphere; if so, return the intersecting z values. z1 is closer to the eye */ static int HitSphere(struct Sphere *s, double x, double y, double z[2]) { double zsq; x -= s->cx; y -= s->cy; zsq = s->r * s->r - (x * x + y * y); if (zsq < 0) { return 0; } else { zsq = sqrt(zsq); z[0] = s->cz - zsq; z[1] = s->cz + zsq; return 1; } } static void DrawSphere(double k, double ambient) { int i, j, hit_result; double x, y, vec[3], zb[2], zs[2]; for (i = floor(pos_.cy - pos_.r); i <= ceil(pos_.cy + pos_.r); i++) { y = i + .5L; for (j = floor(pos_.cx - 2 * pos_.r); j <= ceil(pos_.cx + 2 * pos_.r); j++) { x = .5L * (j - pos_.cx) + .5L + pos_.cx; if (!HitSphere(&pos_, x, y, zb)) { /* ray lands in blank space, draw bg */ hit_result = 0; } else if (!HitSphere(&neg_, x, y, zs)) { /* ray hits pos_ sphere but not neg_, draw pos_ sphere surface */ hit_result = 1; } else if (zs[0] > zb[0]) { /* ray hits both, but pos_ front surface is closer */ hit_result = 1; } else if (zs[1] > zb[1]) { /* pos_ sphere surface is inside neg_ sphere, show bg */ hit_result = 0; } else if (zs[1] > zb[0]) { /* back surface on neg_ sphere is inside pos_ sphere, the only place where neg_ sphere surface will be shown */ hit_result = 2; } else { hit_result = 1; } switch (hit_result) { case 0: WRITE("\e[0m "); continue; case 1: vec[0] = x - pos_.cx; vec[1] = y - pos_.cy; vec[2] = zb[0] - pos_.cz; break; default: vec[0] = neg_.cx - x; vec[1] = neg_.cy - y; vec[2] = neg_.cz - zs[1]; break; } Normalize(vec); WRITE( kShades[min(ARRAYLEN(kShades) - 1, max(0, lround((1 - (pow(Dot(light_, vec), k) + ambient)) * (ARRAYLEN(kShades) - 1))))]); } WRITE("\e[0m\n"); } fflush(stdout); } int main() { double ang; struct termios old; WRITE("\e[?25l"); if (!setjmp(jb_)) { signal(SIGINT, OnCtrlC); ang = 0; for (;;) { WRITE("\e[H"); light_[1] = cosl(ang * 2); sincos(ang, &light_[0], &light_[2]); Normalize(light_); ang += .05L; DrawSphere(1.5L, .01L); usleep(1.L / FRAMERATE * 1e6); } } WRITE("\e[0m\e[H\e[J\e[?25h"); return 0; }
3,963
141
jart/cosmopolitan
false
cosmopolitan/tool/viz/xterm256effective.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 "dsp/tty/quant.h" #include "libc/fmt/fmt.h" #include "libc/intrin/bits.h" #include "libc/intrin/xchg.internal.h" #include "libc/math.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" /* #define ROUND(x) x */ /* #define RT int */ /* #define R1 1 */ /* #define R2 2 */ /* #define R3 3 */ #define RT float #define MUL(x, y) ((x) * (y)) #define RND(x) roundf(x) #define R1 0.25f #define R2 0.50f #define R3 0.75f #define rgb_t struct TtyRgb forceinline RT lerp(RT x, RT y, RT d) { return x * (1.0 - d) + y * d; } forceinline int lerp255(RT x, RT y, RT d) { return lerp(x / 255.0, y / 255.0, d) * 255.0; } forceinline rgb_t rgblerp(rgb_t x, rgb_t y, RT d) { return (rgb_t){lerp255(x.r, y.r, d), lerp255(x.g, y.g, d), lerp255(x.b, y.b, d)}; } forceinline rgb_t getquant(unsigned xt) { return g_ansi2rgb_[xt]; } forceinline unsigned dist(int x, int y) { return x - y; } forceinline unsigned sqr(int x) { return x * x; } forceinline unsigned rgbdist(rgb_t x, rgb_t y) { return sqrt(sqr(dist(x.r, y.r)) + sqr(dist(x.g, y.g)) + sqr(dist(x.b, y.b))); } bool b; rgb_t rgb, cc, c1, c2; unsigned i, j, k, m, n, x, y; char buf[128]; /* 0125 025 067-29 # '░' bg=0352 fg=0306 → ░░░ */ /* 0125 025 067-29 # '▓' bg=0306 fg=0352 → ▓▓▓ */ /* 0125 055 067-29 # '░' bg=0352 fg=0314 → ░░░ */ int main(int argc, char *argv[]) { /* memcpy(g_ansi2rgb_, &kTangoPalette, sizeof(kTangoPalette)); */ /* i = 21; */ /* j = 22; */ /* c1 = getquant(i); */ /* c2 = getquant(j); */ /* cc = rgblerp(c1, c2, R1); */ /* printf("rgblerp((%3d,%3d,%3d), (%3d,%3d,%3d),4) → (%3d,%3d,%3d)\n", c1.r, */ /* c1.g, c1.b, c2.r, c2.g, c2.b, cc.r, cc.g, cc.b); */ /* exit(0); */ for (m = 16; m < 256; m += 6) { for (n = 16; n < 256; n += 6) { printf("------------------------------------------------------------\n"); i = m; j = n; b = false; while (i < m + 6) { printf("\n"); cc = getquant(i); sprintf(buf, "\e[48;5;%dm ", i); printf("0x%02x%02x%02x, %d,%d,0\t/* 0x%02x%02x%02x " " + ' ' bg=%3d → %s \e[0m */\n", cc.b, cc.g, cc.r, i, 0, getquant(i).r, getquant(i).g, getquant(i).b, i, buf); #if 0 sprintf(buf, "\e[38;5;%dm███", i); printf("0x%08x 0x%02x%02x%02x\t" " '█' fg=%3d → %s\e[0m\n", cc.b, cc.g, cc.r, strlen(buf), i, buf); #endif for (x = i; x < i + 1; ++x) { for (y = j; y < j + 1; ++y) { for (k = 0; k < 2; ++k) { if (x > y /* && */ /* rgbdist(getquant(x), getquant(y)) < 49744125 / 16 */ /* && ((32 <= x && x <= 232) && (32 <= y && y <= 232)) && */ /* (cc.r > 0137 && cc.g > 0137 && cc.b > 0137) */) { sprintf(buf, "\e[48;5;%d;38;5;%dm░░░", x, y); cc = rgblerp(getquant(x), getquant(y), R1); printf("0x%02x%02x%02x, %d,%d,1\t/* 0x%02x%02x%02x + " "0x%02x%02x%02x" " + '░' bg=%3d fg=%3d → " "\e[48;5;%dm \e[48;5;%dm " "%s\e[48;2;%d;%d;%dm \e[0m */\n", cc.b, cc.g, cc.r, x, y, getquant(x).r, getquant(x).g, getquant(x).b, getquant(y).r, getquant(y).g, getquant(y).b, x, y, x, y, buf, cc.r, cc.g, cc.b); sprintf(buf, "\e[48;5;%d;38;5;%dm▒▒▒", x, y); cc = rgblerp(getquant(x), getquant(y), R2); printf("0x%02x%02x%02x, %d,%d,2\t/* 0x%02x%02x%02x + " "0x%02x%02x%02x" " + '▒' bg=%3d fg=%3d → " "\e[48;5;%dm \e[48;5;%dm " "%s\e[48;2;%d;%d;%dm \e[0m */\n", cc.b, cc.g, cc.r, x, y, getquant(x).r, getquant(x).g, getquant(x).b, getquant(y).r, getquant(y).g, getquant(y).b, x, y, x, y, buf, cc.r, cc.g, cc.b); sprintf(buf, "\e[48;5;%d;38;5;%dm▓▓▓", x, y); cc = rgblerp(getquant(x), getquant(y), R3); printf("0x%02x%02x%02x, %d,%d,3\t/* 0x%02x%02x%02x + " "0x%02x%02x%02x" " + '▓' bg=%3d fg=%3d → " "\e[48;5;%dm \e[48;5;%dm " "%s\e[48;2;%d;%d;%dm \e[0m */\n", cc.b, cc.g, cc.r, x, y, getquant(x).r, getquant(x).g, getquant(x).b, getquant(y).r, getquant(y).g, getquant(y).b, x, y, x, y, buf, cc.r, cc.g, cc.b); } #if 0 sprintf(buf, "\e[48;5;%d;38;5;%dm▓▓▓", x, y); cc = rgblerp((c1 = getquant(x)), (c2 = getquant(y)), R3); printf("0%03o%03o%03o\t# '▓' bg=%3d fg=%3d → " "%s\e[48;2;%d;%d;%dm \e[0m\n", cc.b, cc.g, cc.r, strlen(buf), x, y, buf, lerp255(c1.r, c2.r, R3), lerp255(c1.g, c2.g, R3), lerp255(c1.b, c2.b, R3)); #endif xchg(&x, &y); } } } ++i; ++j; } } } /* for (i = 0; i < 255; ++i) { */ /* for (j = 0; j < 255; ++j) { */ /* for (k = 0; k < 255; ++k) { */ /* printf("0%03o%03o%03o\n", i, j, k); */ /* } */ /* } */ /* } */ return 0; }
7,497
184
jart/cosmopolitan
false
cosmopolitan/tool/viz/printpeb.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/calls/calls.h" #include "libc/calls/internal.h" #include "libc/dce.h" #include "libc/intrin/safemacros.internal.h" #include "libc/log/log.h" #include "libc/mem/copyfd.internal.h" #include "libc/nt/dll.h" #include "libc/nt/enum/filetype.h" #include "libc/nt/enum/startf.h" #include "libc/nt/files.h" #include "libc/nt/process.h" #include "libc/nt/runtime.h" #include "libc/nt/struct/ldr.h" #include "libc/nt/struct/ldrdatatableentry.h" #include "libc/nt/struct/linkedlist.h" #include "libc/nt/struct/peb.h" #include "libc/nt/struct/systeminfo.h" #include "libc/nt/struct/teb.h" #include "libc/nt/struct/unicodestring.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/o.h" #include "libc/time/time.h" #include "tool/decode/lib/flagger.h" #include "tool/decode/lib/idname.h" #ifdef __x86_64__ char *GetString(struct NtUnicodeString *s) { static char buf[1024]; unsigned len = min(sizeof(buf) - 1, s->Length); for (unsigned i = 0; i < len; ++i) { buf[i] = (unsigned char)s->Data[i]; } buf[len] = '\0'; return &buf[0]; } int NextBestThing(void) { int64_t fd = open("/proc/self/maps", O_RDONLY); posix_fadvise(fd, 0, 0, MADV_SEQUENTIAL); ssize_t wrote; while ((wrote = _copyfd(fd, 1, -1)) != -1) { if (wrote == 0) break; } close(fd); return 0; } const struct IdName kNtStartfFlagNames[] = { {kNtStartfUseshowwindow, "kNtStartfUseshowwindow"}, {kNtStartfUsesize, "kNtStartfUsesize"}, {kNtStartfUseposition, "kNtStartfUseposition"}, {kNtStartfUsecountchars, "kNtStartfUsecountchars"}, {kNtStartfUsefillattribute, "kNtStartfUsefillattribute"}, {kNtStartfRunfullscreen, "kNtStartfRunfullscreen"}, {kNtStartfForceonfeedback, "kNtStartfForceonfeedback"}, {kNtStartfForceofffeedback, "kNtStartfForceofffeedback"}, {kNtStartfUsestdhandles, "kNtStartfUsestdhandles"}, {kNtStartfUsehotkey, "kNtStartfUsehotkey"}, {kNtStartfTitleislinkname, "kNtStartfTitleislinkname"}, {kNtStartfTitleisappid, "kNtStartfTitleisappid"}, {kNtStartfPreventpinning, "kNtStartfPreventpinning"}, {kNtStartfUntrustedsource, "kNtStartfUntrustedsource"}, {0, 0}, }; noasan void PrintStartupInfo(void) { #if 0 printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § startup info │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); #define X(D, F) \ printf("%s.%-22s= " D "\n", "__nt_startupinfo", #F, __nt_startupinfo.F); X("%u", cb); X("%p", lpReserved); X("%hs", lpDesktop); X("%hs", lpTitle); X("%u", dwX); X("%u", dwY); X("%u", dwXSize); X("%u", dwYSize); X("%u", dwXCountChars); X("%u", dwYCountChars); X("%u", dwFillAttribute); printf("%s.%-22s: %s\n", "__nt_startupinfo", "dwFlags", RecreateFlags(kNtStartfFlagNames, __nt_startupinfo.dwFlags)); X("%hu", wShowWindow); X("%hu", cbReserved2); X("%s", lpReserved2); X("%ld", hStdInput); X("%ld", hStdOutput); X("%ld", hStdError); #undef X #endif } void PrintSystemInfo(void) { #if 0 printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § system info │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); #define X(D, F) \ printf("%s.%-28s= " D "\n", "__nt_systeminfo", #F, __nt_systeminfo.F); X("%08x", dwOemId); X("%04hx", wProcessorArchitecture); X("%d", dwPageSize); X("%p", lpMinimumApplicationAddress); X("%p", lpMaximumApplicationAddress); X("%p", dwActiveProcessorMask); X("%u", dwNumberOfProcessors); X("%u", dwProcessorType); X("%u", dwAllocationGranularity); X("%hu", wProcessorLevel); X("%hu", wProcessorRevision); #undef X #endif } const char *ft2str(int ft) { if (ft == kNtFileTypeUnknown) return "kNtFileTypeUnknown"; if (ft == kNtFileTypeDisk) return "kNtFileTypeDisk"; if (ft == kNtFileTypeChar) return "kNtFileTypeChar"; if (ft == kNtFileTypePipe) return "kNtFileTypePipe"; if (ft == kNtFileTypeRemote) return "kNtFileTypeRemote"; return "wut?"; } void PrintStdioInfo(void) { printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § stdio info │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); printf("%s: %ld (%s)\n", "g_fds.p[0].handle", g_fds.p[0].handle, ft2str(GetFileType(g_fds.p[0].handle))); printf("%s: %ld (%s)\n", "g_fds.p[1].handle", g_fds.p[1].handle, ft2str(GetFileType(g_fds.p[1].handle))); printf("%s: %ld (%s)\n", "g_fds.p[2].handle", g_fds.p[2].handle, ft2str(GetFileType(g_fds.p[2].handle))); } noasan void PrintTeb(void) { GetCurrentProcessId(); SetLastError(0x1234); printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § teb? │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x00, "NtGetSeh()", _NtGetSeh()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x08, "NtGetStackHigh()", _NtGetStackHigh()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x10, "NtGetStackLow()", _NtGetStackLow()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x18, "_NtGetSubsystemTib()", _NtGetSubsystemTib()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x20, "NtGetFib()", _NtGetFib()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x30, "NtGetTeb()", NtGetTeb()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x38, "NtGetEnv()", _NtGetEnv()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x40, "NtGetPid()", NtGetPid()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x48, "NtGetTid()", NtGetTid()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x50, "NtGetRpc()", _NtGetRpc()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x58, "NtGetTls()", _NtGetTls()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x60, "NtGetPeb()", NtGetPeb()); printf("gs:0x%02x: %-39s = 0x%lx\n", 0x68, "NtGetErr()", NtGetErr()); } void PrintPeb(void) { struct NtPeb *peb = NtGetPeb(); printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § peb │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); printf("0x%04x: %-40s = %u\n", offsetof(struct NtPeb, InheritedAddressSpace), "InheritedAddressSpace", (unsigned)peb->InheritedAddressSpace); printf("0x%04x: %-40s = %u\n", offsetof(struct NtPeb, ReadImageFileExecOptions), "ReadImageFileExecOptions", (unsigned)peb->ReadImageFileExecOptions); printf("0x%04x: %-40s = %u\n", offsetof(struct NtPeb, BeingDebugged), "BeingDebugged", (unsigned)peb->BeingDebugged); printf("0x%04x: %-40s = %u\n", offsetof(struct NtPeb, __wut1), "__wut1", (unsigned)peb->__wut1); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, Mutant), "Mutant", peb->Mutant); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ImageBaseAddress), "ImageBaseAddress", peb->ImageBaseAddress); /* struct NtLdr *Ldr; */ printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ProcessParameters), "ProcessParameters", peb->ProcessParameters); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, SubSystemData), "SubSystemData", peb->SubSystemData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ProcessHeap), "ProcessHeap", peb->ProcessHeap); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, FastPebLock), "FastPebLock", peb->FastPebLock); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, __wut3), "__wut3", peb->__wut3); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, __wut4), "__wut4", peb->__wut4); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, __wut5), "__wut5", peb->__wut5); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, KernelCallbackTable), "KernelCallbackTable", peb->KernelCallbackTable); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, UserSharedInfoPtr), "UserSharedInfoPtr", peb->UserSharedInfoPtr); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, SystemReserved), "SystemReserved", peb->SystemReserved); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, __wut6), "__wut6", peb->__wut6); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, __wut7), "__wut7", peb->__wut7); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, TlsExpansionCounter), "TlsExpansionCounter", peb->TlsExpansionCounter); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, TlsBitmap), "TlsBitmap", peb->TlsBitmap); printf("0x%04x: %-40s = 0x%x 0x%x\n", offsetof(struct NtPeb, TlsBitmapBits), "TlsBitmapBits", peb->TlsBitmapBits[0], peb->TlsBitmapBits[1]); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ReadOnlySharedMemoryBase), "ReadOnlySharedMemoryBase", peb->ReadOnlySharedMemoryBase); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, __wut8), "__wut8", peb->__wut8); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ReadOnlyStaticServerData), "ReadOnlyStaticServerData", peb->ReadOnlyStaticServerData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, AnsiCodePageData), "AnsiCodePageData", peb->AnsiCodePageData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, OemCodePageData), "OemCodePageData", peb->OemCodePageData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, UnicodeCaseTableData), "UnicodeCaseTableData", peb->UnicodeCaseTableData); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, NumberOfProcessors), "NumberOfProcessors", peb->NumberOfProcessors); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, NtGlobalFlag), "NtGlobalFlag", peb->NtGlobalFlag); printf("0x%04x: %-40s = %ld\n", offsetof(struct NtPeb, CriticalSectionTimeout), "CriticalSectionTimeout", peb->CriticalSectionTimeout); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, HeapSegmentReserve), "HeapSegmentReserve", peb->HeapSegmentReserve); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, HeapSegmentCommit), "HeapSegmentCommit", peb->HeapSegmentCommit); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, HeapDeCommitTotalFreeThreshold), "HeapDeCommitTotalFreeThreshold", peb->HeapDeCommitTotalFreeThreshold); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, HeapDeCommitFreeBlockThreshold), "HeapDeCommitFreeBlockThreshold", peb->HeapDeCommitFreeBlockThreshold); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, NumberOfHeaps), "NumberOfHeaps", peb->NumberOfHeaps); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, MaximumNumberOfHeaps), "MaximumNumberOfHeaps", peb->MaximumNumberOfHeaps); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ProcessHeaps), "ProcessHeaps", peb->ProcessHeaps); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, GdiSharedHandleTable), "GdiSharedHandleTable", peb->GdiSharedHandleTable); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ProcessStarterHelper), "ProcessStarterHelper", peb->ProcessStarterHelper); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, GdiDCAttributeList), "GdiDCAttributeList", peb->GdiDCAttributeList); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, LoaderLock), "LoaderLock", peb->LoaderLock); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, OSMajorVersion), "OSMajorVersion", peb->OSMajorVersion); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, OSMinorVersion), "OSMinorVersion", peb->OSMinorVersion); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtPeb, OSBuildNumber), "OSBuildNumber", peb->OSBuildNumber); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtPeb, OSCSDVersion), "OSCSDVersion", peb->OSCSDVersion); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, OSPlatformId), "OSPlatformId", peb->OSPlatformId); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, ImageSubsystem), "ImageSubsystem", peb->ImageSubsystem); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtPeb, ImageSubsystemMajorVersion), "ImageSubsystemMajorVersion", peb->ImageSubsystemMajorVersion); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ImageSubsystemMinorVersion), "ImageSubsystemMinorVersion", peb->ImageSubsystemMinorVersion); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ImageProcessAffinityMask), "ImageProcessAffinityMask", peb->ImageProcessAffinityMask); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ActiveProcessAffinityMask), "ActiveProcessAffinityMask", peb->ActiveProcessAffinityMask); /* "0x%lx", GdiHandleBuffer[38 - __SIZEOF_POINTER__]; */ printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, PostProcessInitRoutine), "PostProcessInitRoutine", peb->PostProcessInitRoutine); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, TlsExpansionBitmap), "TlsExpansionBitmap", peb->TlsExpansionBitmap); /* "0x%x", TlsExpansionBitmapBits[32]; */ printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, SessionId), "SessionId", peb->SessionId); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, AppCompatFlags), "AppCompatFlags", peb->AppCompatFlags); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, AppCompatFlagsUser), "AppCompatFlagsUser", peb->AppCompatFlagsUser); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, pShimData), "pShimData", peb->pShimData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, AppCompatInfo), "AppCompatInfo", peb->AppCompatInfo); printf("0x%04x: %-40s = \"%s\"\n", offsetof(struct NtPeb, CSDVersion), "CSDVersion", GetString(&peb->CSDVersion)); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ActivationContextData), "ActivationContextData", peb->ActivationContextData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, ProcessAssemblyStorageMap), "ProcessAssemblyStorageMap", peb->ProcessAssemblyStorageMap); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, SystemDefaultActivationContextData), "SystemDefaultActivationContextData", peb->SystemDefaultActivationContextData); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, SystemAssemblyStorageMap), "SystemAssemblyStorageMap", peb->SystemAssemblyStorageMap); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtPeb, MinimumStackCommit), "MinimumStackCommit", peb->MinimumStackCommit); } void PrintPebLdr(void) { printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § peb » ldr │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, SizeOfThis), "SizeOfThis", NtGetPeb()->Ldr->SizeOfThis); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, IsInitialized), "IsInitialized", NtGetPeb()->Ldr->IsInitialized); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, SsHandle), "SsHandle", NtGetPeb()->Ldr->SsHandle); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, InLoadOrderModuleList), "InLoadOrderModuleList", NtGetPeb()->Ldr->InLoadOrderModuleList); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, InMemoryOrderModuleList), "InMemoryOrderModuleList", NtGetPeb()->Ldr->InMemoryOrderModuleList); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdr, InInitOrderModuleList), "InInitOrderModuleList", NtGetPeb()->Ldr->InInitOrderModuleList); } void PrintModulesLoadOrder(void) { { printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § modules » load order │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); struct NtLinkedList *head = &NtGetPeb()->Ldr->InLoadOrderModuleList; struct NtLinkedList *ldr = head->Next; do { const struct NtLdrDataTableEntry *dll = (const struct NtLdrDataTableEntry *)ldr; /* struct NtLinkedList InLoadOrderLinks; /\* msdn:reserved *\/ */ /* struct NtLinkedList InMemoryOrderLinks; */ /* struct NtLinkedList InInitOrderLinks; /\* msdn:reserved *\/ */ printf("%p\n", ldr); printf("%p vs. %p\n", dll, GetModuleHandleW(dll->FullDllName.Data)); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, DllBase), "DllBase", dll->DllBase); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, EntryPoint), "EntryPoint", dll->EntryPoint); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtLdrDataTableEntry, SizeOfImage), "SizeOfImage", dll->SizeOfImage); printf("0x%04x: %-40s = \"%s\"\n", offsetof(struct NtLdrDataTableEntry, FullDllName), "FullDllName", GetString(&dll->FullDllName)); printf("0x%04x: %-40s = \"%s\"\n", offsetof(struct NtLdrDataTableEntry, BaseDllName), "BaseDllName", GetString(&dll->BaseDllName)); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtLdrDataTableEntry, Flags), "Flags", dll->Flags); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtLdrDataTableEntry, Load_Count), "Load_Count", dll->Load_Count); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtLdrDataTableEntry, TlsIndex), "TlsIndex", dll->TlsIndex); /* union { */ /* struct NtLinkedList HashLinks; */ /* struct { */ /* void *SectionPointer; */ /* uint32_t CheckSum; */ /* }; */ /* }; */ /* union { */ /* void *LoadedImports; */ /* uint32_t TimeDateStamp; */ /* }; */ printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, EntryPointActivationContext), "EntryPointActivationContext", dll->EntryPointActivationContext); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, PatchInformation), "PatchInformation", dll->PatchInformation); /* struct NtLinkedList ForwarderLinks; */ /* struct NtLinkedList ServiceTagLinks; */ /* struct NtLinkedList StaticLinks; */ printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, ContextInformation), "ContextInformation", dll->ContextInformation); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, OriginalBase), "OriginalBase", dll->OriginalBase); printf("0x%04x: %-40s = %ld\n", offsetof(struct NtLdrDataTableEntry, LoadTime), "LoadTime", dll->LoadTime); printf("\n"); } while ((ldr = ldr->Next) && ldr != head); } } void PrintModulesMemoryOrder(void) { { printf("\n\ ╔──────────────────────────────────────────────────────────────────────────────╗\n\ │ new technology § modules » memory order │\n\ ╚──────────────────────────────────────────────────────────────────────────────╝\n\ \n"); struct NtLinkedList *head = &NtGetPeb()->Ldr->InMemoryOrderModuleList; struct NtLinkedList *ldr = head->Next; do { const struct NtLdrDataTableEntry *dll = (const struct NtLdrDataTableEntry *)ldr; /* struct NtLinkedList InLoadOrderLinks; /\* msdn:reserved *\/ */ /* struct NtLinkedList InMemoryOrderLinks; */ /* struct NtLinkedList InInitOrderLinks; /\* msdn:reserved *\/ */ printf("%p\n", dll); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, DllBase), "DllBase", dll->DllBase); printf("0x%04x: %-40s = 0x%lx\n", offsetof(struct NtLdrDataTableEntry, EntryPoint), "EntryPoint", dll->EntryPoint); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtLdrDataTableEntry, SizeOfImage), "SizeOfImage", dll->SizeOfImage); printf("0x%04x: %-40s = \"%s\"\n", offsetof(struct NtLdrDataTableEntry, FullDllName), "FullDllName", GetString(&dll->FullDllName)); printf("0x%04x: %-40s = \"%s\"\n", offsetof(struct NtLdrDataTableEntry, BaseDllName), "BaseDllName", GetString(&dll->BaseDllName)); printf("0x%04x: %-40s = 0x%x\n", offsetof(struct NtLdrDataTableEntry, Flags), "Flags", dll->Flags); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtLdrDataTableEntry, Load_Count), "Load_Count", dll->Load_Count); printf("0x%04x: %-40s = %hu\n", offsetof(struct NtLdrDataTableEntry, TlsIndex), "TlsIndex", dll->TlsIndex); /* /\* union { *\/ */ /* /\* struct NtLinkedList HashLinks; *\/ */ /* /\* struct { *\/ */ /* /\* void *SectionPointer; *\/ */ /* /\* uint32_t CheckSum; *\/ */ /* /\* }; *\/ */ /* /\* }; *\/ */ /* /\* union { *\/ */ /* /\* void *LoadedImports; *\/ */ /* /\* uint32_t TimeDateStamp; *\/ */ /* /\* }; *\/ */ /* printf("0x%04x: %-40s = 0x%lx\n", */ /* offsetof(struct NtLdrDataTableEntry, * EntryPointActivationContext), */ /* "EntryPointActivationContext", * dll->EntryPointActivationContext); */ /* printf("0x%04x: %-40s = 0x%lx\n", */ /* offsetof(struct NtLdrDataTableEntry, PatchInformation), */ /* "PatchInformation", dll->PatchInformation); */ /* /\* struct NtLinkedList ForwarderLinks; *\/ */ /* /\* struct NtLinkedList ServiceTagLinks; *\/ */ /* /\* struct NtLinkedList StaticLinks; *\/ */ /* printf("0x%04x: %-40s = 0x%lx\n", */ /* offsetof(struct NtLdrDataTableEntry, ContextInformation), */ /* "ContextInformation", dll->ContextInformation); */ /* printf("0x%04x: %-40s = 0x%lx\n", */ /* offsetof(struct NtLdrDataTableEntry, OriginalBase), * "OriginalBase", */ /* dll->OriginalBase); */ /* printf("0x%04x: %-40s = %ld\n", */ /* offsetof(struct NtLdrDataTableEntry, LoadTime), "LoadTime", */ /* dll->LoadTime); */ printf("\n"); } while ((ldr = ldr->Next) && ldr != head); } } int main(int argc, char *argv[]) { if (IsLinux()) { return NextBestThing(); } if (!IsWindows()) { fprintf(stderr, "error: this tool is intended for windows\n"); return 1; } PrintStartupInfo(); PrintSystemInfo(); PrintStdioInfo(); PrintTeb(); PrintPeb(); PrintPebLdr(); PrintModulesLoadOrder(); PrintModulesMemoryOrder(); return 0; } #endif /* __x86_64__ */
28,272
543
jart/cosmopolitan
false
cosmopolitan/tool/viz/float2bin.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 "libc/stdio/stdio.h" #include "third_party/gdtoa/gdtoa.h" const char kDoubleBits[] = "\ ┌sign\n\ │ ┌exponent\n\ │ │ ┌fraction\n\ │ │ │\n\ │┌┴────────┐┌┴─────────────────────────────────────────────────┐\n"; const char kLongDoubleBits[] = "\ ┌sign\n\ │ ┌exponent\n\ │ │ ┌intpart\n\ │ │ │ ┌fraction\n\ │ │ │ │\n\ │┌┴────────────┐│┌┴────────────────────────────────────────────────────────────┐\n"; int main(int argc, char *argv[]) { int i; union { double f; uint64_t i; } u; if (argc <= 1) return 1; fputs(kDoubleBits, stdout); for (i = 1; i < argc; ++i) { u.f = strtod(argv[i], 0); printf("%064lb %.15g\n", u.i, u.f); } return 0; }
2,899
51
jart/cosmopolitan
false
cosmopolitan/tool/viz/tabalign.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/safemacros.internal.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/arraylist.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/strwidth.h" #include "libc/str/unicode.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" #define kOneTrueTabWidth 8 struct Pool { size_t i, n; char *p; }; struct Lines { size_t i, n; struct Line { uint16_t off; uint16_t col; int32_t line; } * p; }; static bool chunk_; static FILE *fi_, *fo_; static struct Pool pool_; static struct Lines lines_; static size_t mincol_, col_, maxcol_, linecap_; static char *inpath_, *outpath_, *delim_, *line_; wontreturn void usage(int rc, FILE *f) { fprintf(f, "%s%s%s\n", "Usage: ", program_invocation_name, " [-c] [-m MINCOL] [-M MAXCOL] [-F DELIM] [-o FILE] [FILE...]\n" "\n" " This program aligns monospace text. It's aware of tabs,\n" " color codes, wide characters, combining characters etc.\n"); exit(rc); } void getopts(int *argc, char *argv[]) { int opt; delim_ = "#"; outpath_ = "-"; while ((opt = getopt(*argc, argv, "?hco:m:M:F:")) != -1) { switch (opt) { case 'm': mincol_ = strtol(optarg, NULL, 0); break; case 'M': maxcol_ = strtol(optarg, NULL, 0); break; case 'c': chunk_ = true; break; case 'o': outpath_ = optarg; break; case 'F': delim_ = optarg; break; case '?': case 'h': usage(EXIT_SUCCESS, stdout); default: usage(EX_USAGE, stderr); } } if (optind == *argc) { argv[(*argc)++] = "-"; } } void flush(void) { size_t i, j; const char *s; struct Line l; col_ = roundup(col_ + 1, kOneTrueTabWidth); if (maxcol_) col_ = min(col_, maxcol_); for (i = 0; i < lines_.i; ++i) { l = lines_.p[i]; s = &pool_.p[l.line]; if (l.off < USHRT_MAX) { fwrite(s, l.off, 1, fo_); for (j = l.col; j < col_;) { fputc('\t', fo_); if (j % kOneTrueTabWidth == 0) { j += 8; } else { j += kOneTrueTabWidth - (j & (kOneTrueTabWidth - 1)); } } fwrite(s + l.off, strlen(s) - l.off, 1, fo_); } else { fwrite(s, strlen(s), 1, fo_); } fputc('\n', fo_); } col_ = mincol_; pool_.i = 0; lines_.i = 0; } void processfile(void) { char *p; int col, s; size_t off, len; while ((getline(&line_, &linecap_, fi_)) != -1) { _chomp(line_); len = strlen(line_); s = concat(&pool_, line_, len + 1); if (len < USHRT_MAX) { if ((p = strstr(line_, delim_))) { off = p - line_; col = strnwidth(line_, off, 0); if (col < USHRT_MAX) { col_ = max(col_, col); append(&lines_, &((struct Line){.line = s, .off = off, .col = col})); continue; } } else { if (chunk_) { flush(); fputs(line_, fo_); fputc('\n', fo_); continue; } } } append(&lines_, &((struct Line){.line = s, .off = 0xffff, .col = 0xffff})); } } int main(int argc, char *argv[]) { size_t i; getopts(&argc, argv); CHECK_NOTNULL((fo_ = fopen(outpath_, "w"))); for (i = optind; i < argc; ++i) { CHECK_NOTNULL((fi_ = fopen((inpath_ = argv[i]), "r"))); processfile(); CHECK_NE(-1, fclose(fi_)); fi_ = 0; } flush(); CHECK_NE(-1, fclose(fo_)); fo_ = 0; free(lines_.p); free(pool_.p); free(line_); return 0; }
5,570
178
jart/cosmopolitan
false
cosmopolitan/tool/viz/rsastrength.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 "libc/fmt/conv.h" #include "libc/math.h" #include "libc/stdio/stdio.h" int main(int argc, char *argv[]) { int i, x, y; for (i = 1; i < argc; ++i) { x = atoi(argv[i]); y = round( (1.923 * cbrt(x * log(2)) * cbrt(log(x * log(2)) * log(x * log(2))) - 4.69) / log(2)); printf("%4d %4d\n", x, y); } return 0; }
2,197
35
jart/cosmopolitan
false
cosmopolitan/tool/viz/xterm256gradient.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 "libc/math.h" #include "libc/stdio/stdio.h" #define N 8 #define SQR(X) ((X) * (X)) static const uint8_t kXtermCube[6] = {0, 0137, 0207, 0257, 0327, 0377}; static int rgb2xterm256(int r, int g, int b) { int cerr, gerr, ir, ig, ib, gray, grai, cr, cg, cb, gv; gray = round(r * .299 + g * .587 + b * .114); grai = gray > 238 ? 23 : (gray - 3) / 10; ir = r < 48 ? 0 : r < 115 ? 1 : (r - 35) / 40; ig = g < 48 ? 0 : g < 115 ? 1 : (g - 35) / 40; ib = b < 48 ? 0 : b < 115 ? 1 : (b - 35) / 40; cr = kXtermCube[ir]; cg = kXtermCube[ig]; cb = kXtermCube[ib]; gv = 8 + 10 * grai; cerr = SQR(cr - r) + SQR(cg - g) + SQR(cb - b); gerr = SQR(gv - r) + SQR(gv - g) + SQR(gv - b); if (cerr <= gerr) { return 16 + 36 * ir + 6 * ig + ib; } else { return 232 + grai; } } int main(int argc, char *argv[]) { double d; int i, j, x; int r, g, b; double G[N][3]; double rgb[2][3] = { {1, 0, 0}, {0, 1, 0}, }; for (i = 0; i < N; ++i) { for (j = 0; j < 3; ++j) { d = (rgb[1][j] - rgb[0][j]) / (N - 1); G[i][j] = rgb[0][j] + d * i; } } for (i = 0; i < N; ++i) { r = round(G[i][0] * 255); g = round(G[i][1] * 255); b = round(G[i][2] * 255); x = rgb2xterm256(r, g, b); printf("\e[38;5;232;48;5;%dmabcdefg \e[0m %3d " "\e[38;5;232;48;2;%d;%d;%dmabcdgefg \e[0m " "%3d %3d %3d %f %f %f\n", x, x, r, g, b, r, g, b, G[i][0], G[i][1], G[i][2]); } return 0; }
3,334
78
jart/cosmopolitan
false
cosmopolitan/tool/viz/dumphexc.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 "libc/fmt/fmt.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/append.h" #include "libc/stdio/hex.internal.h" #include "libc/stdio/stdio.h" /** * @fileoverview Hex String Literal Converter, e.g. * * $ echo hello | o/tool/viz/dumphexc.com * "\ * \x68\x65\x6c\x6c\x6f\x0a" */ int main(int argc, char *argv[]) { char *p; size_t n, g; char *b = 0; char buf[512]; while ((g = fread(buf, 1, sizeof(buf), stdin))) { appendd(&b, buf, g); } if (!ferror(stdin)) { p = DumpHexc(b, appendz(b).i, &n); fwrite(p, 1, n, stdout); free(p); } printf("\n"); return ferror(stdin) || ferror(stdout) ? 1 : 0; }
2,525
50
jart/cosmopolitan
false
cosmopolitan/tool/viz/cpuid.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/intrin/bits.h" #include "libc/intrin/kprintf.h" #include "libc/log/color.internal.h" #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/nexgen32e/cpuid4.internal.h" #include "libc/nexgen32e/nexgen32e.h" #include "libc/nexgen32e/rdtscp.h" #include "libc/nexgen32e/x86feature.h" #include "libc/nexgen32e/x86info.h" #include "libc/stdio/stdio.h" #include "libc/time/time.h" #include "libc/x/xasprintf.h" #include "tool/decode/lib/idname.h" #include "tool/decode/lib/x86idnames.h" #ifdef __x86_64__ #define CANIUSE(FEATURE) caniuse(#FEATURE, X86_HAVE(FEATURE)) #define SHOW(CONSTANT) show(#CONSTANT, CONSTANT) static void caniuse(const char *feature, bool present) { printf("%-20s%s%s%s\n", feature, present ? GREEN : RED, present ? "present" : "unavailable", RESET); } static void show(const char *constant, long value) { printf("%-20s%#lx\n", constant, value); } static void decimal(const char *a, long b, const char *c) { printf("%-20s%ld%s\n", a, b, c); } static void showvendor(void) { printf("%.*s%.*s%.*s", 4, &KCPUIDS(0H, EBX), 4, &KCPUIDS(0H, EDX), 4, &KCPUIDS(0H, ECX)); } static void showmodel(void) { if (getx86processormodel(kX86ProcessorModelKey)) { printf(" %s", findnamebyid(kX86MarchNames, getx86processormodel(kX86ProcessorModelKey)->march)); } } static void showstrata(void) { if (getx86processormodel(kX86ProcessorModelKey)) { printf(" (%s %s)", findnamebyid(kX86GradeNames, getx86processormodel(kX86ProcessorModelKey)->grade), "Grade"); } } void showcachesizes(void) { unsigned i; CPUID4_ITERATE(i, { printf("%-19s%s%s %u-way %,7u byte cache w/%s %,5u sets of %u byte lines " "shared across %u threads\n", _gc(xasprintf("Level %u%s", CPUID4_CACHE_LEVEL, CPUID4_CACHE_TYPE == 1 ? " data" : CPUID4_CACHE_TYPE == 2 ? " code" : "")), CPUID4_IS_FULLY_ASSOCIATIVE ? " fully-associative" : "", CPUID4_COMPLEX_INDEXING ? " complexly-indexed" : "", CPUID4_WAYS_OF_ASSOCIATIVITY, CPUID4_CACHE_SIZE_IN_BYTES, CPUID4_PHYSICAL_LINE_PARTITIONS > 1 ? _gc(xasprintf(" %u physically partitioned")) : "", CPUID4_NUMBER_OF_SETS, CPUID4_SYSTEM_COHERENCY_LINE_SIZE, CPUID4_MAX_THREADS_SHARING_CACHE); }); } int main(int argc, char *argv[]) { int x; long tsc_aux; ShowCrashReports(); showvendor(); showmodel(); showstrata(); printf("\n"); if (KCPUIDS(16H, EAX)) { printf("\n"); if ((x = KCPUIDS(16H, EAX) & 0x7fff)) decimal("frequency", x, "mhz"); if ((x = KCPUIDS(16H, EBX) & 0x7fff)) decimal("turbo", x, "mhz"); if ((x = KCPUIDS(16H, ECX) & 0x7fff)) decimal("bus", x, "mhz"); } if (X86_HAVE(HYPERVISOR)) { int ax, cx; char s[4 * 3 + 1]; asm("push\t%%rbx\r\n" "cpuid\r\n" "mov\t%%ebx,0+%2\r\n" "mov\t%%ecx,4+%2\r\n" "mov\t%%edx,8+%2\r\n" "movb\t$0,12+%2\r\n" "pop\t%%rbx" : "=a"(ax), "=c"(cx), "=o"(s) : "0"(0x40000000), "1"(0) : "rdx"); kprintf("Running inside %s (eax=%#x)\n", s, ax); } printf("\n"); SHOW(kX86CpuFamily); SHOW(kX86CpuModel); printf("\n"); SHOW(kX86CpuStepping); SHOW(kX86CpuType); SHOW(kX86CpuModelid); SHOW(kX86CpuExtmodelid); SHOW(kX86CpuFamilyid); SHOW(kX86CpuExtfamilyid); printf("\n"); tsc_aux = rdpid(); show("TSC_AUX", tsc_aux); show(" → core", TSC_AUX_CORE(tsc_aux)); show(" → node", TSC_AUX_NODE(tsc_aux)); printf("\n"); printf("Caches\n"); printf("──────\n"); showcachesizes(); printf("\n"); printf("Features\n"); printf("────────\n"); CANIUSE(ACC); CANIUSE(ACPI); CANIUSE(ADX); CANIUSE(AES); CANIUSE(APIC); CANIUSE(ARCH_CAPABILITIES); CANIUSE(AVX); printf("%-20s%s%s%s%s\n", "AVX2", X86_HAVE(AVX2) ? GREEN : RED, X86_HAVE(AVX2) ? "present" : "unavailable", RESET, (!X86_HAVE(AVX2) && ({ unsigned eax, ebx, ecx, edx; asm("push\t%%rbx\n\t" "cpuid\n\t" "mov\t%%ebx,%1\n\t" "pop\t%%rbx" : "=a"(eax), "=rm"(ebx), "=c"(ecx), "=d"(edx) : "0"(7), "2"(0)); (void)eax; (void)ecx; (void)edx; !!(ebx & (1u << 5)); })) ? " (disabled by operating system)" : ""); CANIUSE(AVX512BW); CANIUSE(AVX512CD); CANIUSE(AVX512DQ); CANIUSE(AVX512ER); CANIUSE(AVX512F); CANIUSE(AVX512IFMA); CANIUSE(AVX512PF); CANIUSE(AVX512VBMI); CANIUSE(AVX512VL); CANIUSE(AVX512_4FMAPS); CANIUSE(AVX512_4VNNIW); CANIUSE(AVX512_BF16); CANIUSE(AVX512_BITALG); CANIUSE(AVX512_VBMI2); CANIUSE(AVX512_VNNI); CANIUSE(AVX512_VP2INTERSECT); CANIUSE(AVX512_VPOPCNTDQ); CANIUSE(BMI); CANIUSE(BMI2); CANIUSE(CID); CANIUSE(CLDEMOTE); CANIUSE(CLFLUSH); CANIUSE(CLFLUSHOPT); CANIUSE(CLWB); CANIUSE(CMOV); CANIUSE(CQM); CANIUSE(CX16); CANIUSE(CX8); CANIUSE(DCA); CANIUSE(DE); CANIUSE(DS); CANIUSE(DSCPL); CANIUSE(DTES64); CANIUSE(ERMS); CANIUSE(EST); CANIUSE(F16C); CANIUSE(FDP_EXCPTN_ONLY); CANIUSE(FLUSH_L1D); CANIUSE(FMA); CANIUSE(FPU); CANIUSE(FSGSBASE); CANIUSE(FXSR); CANIUSE(GBPAGES); CANIUSE(GFNI); CANIUSE(HLE); CANIUSE(HT); CANIUSE(HYPERVISOR); CANIUSE(IA64); CANIUSE(INTEL_PT); CANIUSE(INTEL_STIBP); CANIUSE(INVPCID); CANIUSE(LA57); CANIUSE(LM); CANIUSE(MCA); CANIUSE(MCE); CANIUSE(MD_CLEAR); CANIUSE(MMX); CANIUSE(MOVBE); CANIUSE(MOVDIR64B); CANIUSE(MOVDIRI); CANIUSE(MP); CANIUSE(MPX); CANIUSE(MSR); CANIUSE(MTRR); CANIUSE(MWAIT); CANIUSE(NX); CANIUSE(OSPKE); CANIUSE(OSXSAVE); CANIUSE(PAE); CANIUSE(PAT); CANIUSE(PBE); CANIUSE(PCID); CANIUSE(PCLMUL); CANIUSE(PCONFIG); CANIUSE(PDCM); CANIUSE(PGE); CANIUSE(PKU); CANIUSE(PN); CANIUSE(POPCNT); CANIUSE(PSE); CANIUSE(PSE36); CANIUSE(RDPID); CANIUSE(RDRND); CANIUSE(RDSEED); CANIUSE(RDTSCP); CANIUSE(RDT_A); CANIUSE(RTM); CANIUSE(SDBG); CANIUSE(SELFSNOOP); CANIUSE(SEP); CANIUSE(SHA); CANIUSE(SMAP); CANIUSE(SMEP); CANIUSE(SMX); CANIUSE(SPEC_CTRL); CANIUSE(SPEC_CTRL_SSBD); CANIUSE(SSE); CANIUSE(SSE2); CANIUSE(SSE3); CANIUSE(SSE4_1); CANIUSE(SSE4_2); CANIUSE(SSSE3); CANIUSE(SYSCALL); CANIUSE(TM2); CANIUSE(TME); CANIUSE(TSC); CANIUSE(TSC_ADJUST); CANIUSE(TSC_DEADLINE_TIMER); CANIUSE(TSX_FORCE_ABORT); CANIUSE(UMIP); CANIUSE(VAES); CANIUSE(VME); CANIUSE(VMX); CANIUSE(VPCLMULQDQ); CANIUSE(WAITPKG); CANIUSE(X2APIC); CANIUSE(XSAVE); CANIUSE(XTPR); CANIUSE(ZERO_FCS_FDS); printf("\n"); printf("AMD Stuff\n"); printf("─────────\n"); CANIUSE(3DNOW); CANIUSE(3DNOWEXT); CANIUSE(3DNOWPREFETCH); CANIUSE(ABM); CANIUSE(BPEXT); CANIUSE(CMP_LEGACY); CANIUSE(CR8_LEGACY); CANIUSE(EXTAPIC); CANIUSE(FMA4); CANIUSE(FXSR_OPT); CANIUSE(IBS); CANIUSE(LAHF_LM); CANIUSE(LWP); CANIUSE(MISALIGNSSE); CANIUSE(MMXEXT); CANIUSE(MWAITX); CANIUSE(NODEID_MSR); CANIUSE(OSVW); CANIUSE(OVERFLOW_RECOV); CANIUSE(PERFCTR_CORE); CANIUSE(PERFCTR_LLC); CANIUSE(PERFCTR_NB); CANIUSE(PTSC); CANIUSE(SKINIT); CANIUSE(SMCA); CANIUSE(SSE4A); CANIUSE(SUCCOR); CANIUSE(SVM); CANIUSE(TBM); CANIUSE(TCE); CANIUSE(TOPOEXT); CANIUSE(WDT); CANIUSE(XOP); return 0; } #endif /* __x86_64__ */
9,462
339
jart/cosmopolitan
false
cosmopolitan/tool/viz/derasterize.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 "dsp/tty/itoa8.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/stat.h" #include "libc/calls/termios.h" #include "libc/fmt/conv.h" #include "libc/fmt/fmt.h" #include "libc/intrin/tpenc.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/x86feature.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/madv.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/x/x.h" #include "third_party/getopt/getopt.h" #include "third_party/stb/stb_image.h" #include "third_party/stb/stb_image_resize.h" #ifdef __x86_64__ #define HELPTEXT \ "\n\ NAME\n\ \n\ derasterize - convert pictures to text using unicode ANSI art\n\ \n\ SYNOPSIS\n\ \n\ derasterize [FLAGS] [PNG|JPG|ETC]...\n\ \n\ DESCRIPTION\n\ \n\ This program converts pictures into unicode text and ANSI colors so\n\ that images can be displayed within a terminal. It performs lots of\n\ AVX2 optimized math to deliver the best quality on modern terminals\n\ with 24-bit color support, e.g. Kitty, Gnome Terminal, CMD.EXE, etc\n\ \n\ The default output if fullscreen but can be changed:\n\ -w X\n\ -x X\n\ If X is positive, hardcode the width in tty cells to X\n\ If X is negative, remove as much from the fullscreen width\n\ X may be specified as base 10 decimal, octal, binary, or hex\n\ -h Y\n\ -y Y\n\ If Y is positive, hardcode the height in tty cells to Y\n\ If Y is negative, remove as much from the fullscreen height\n\ May be specified as base 10 decimal, octal, binary, or hex\n\ -m\n\ Use ImageMagick `convert` command to load/scale graphics\n\ -?\n\ -H\n\ Show this help information\n\ \n\ EXAMPLES\n\ \n\ $ ./derasterize.com samples/wave.png > wave.uaart\n\ $ cat wave.uaart\n\ \n\ AUTHORS\n\ \n\ Csdvrx <[email protected]>\n\ Justine Tunney <[email protected]>\n\ " int m_; /* -m [use imagemagick] */ int x_; /* -x WIDTH [in flexidecimal] */ int y_; /* -y HEIGHT [in flexidecimal] */ #define BEST 0 #define FAST 1 #define FASTER 2 #define Mode BEST #if Mode == BEST #define MC 9u /* log2(#) of color combos to consider */ #define GN 35u /* # of glyphs to consider */ #elif Mode == FAST #define MC 6u #define GN 35u #elif Mode == FASTER #define MC 4u #define GN 25u #endif #define CN 3u /* # channels (rgb) */ #define YS 8u /* row stride -or- block height */ #define XS 4u /* column stride -or- block width */ #define GT 44u /* total glyphs */ #define BN (YS * XS) /* # scalars in block/glyph plane */ #define PHIPRIME 0x9E3779B1u extern const uint32_t kGlyphs[]; extern const char16_t kRunes[]; /*───────────────────────────────────────────────────────────────────────────│─╗ │ derasterize § encoding ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ /** * Formats Thompson-Pike variable length integer to array. * * @param p needs at least 8 bytes * @return p + number of bytes written, cf. mempcpy * @note no NUL-terminator is added */ static char *tptoa(char *p, wchar_t x) { unsigned long w; for (w = _tpenc(x); w; w >>= 010) *p++ = w & 0xff; return p; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ derasterize § colors ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static float frgb2lin(float x) { float r1, r2; r1 = x / 12.92f; r2 = pow((x + 0.055) / (1 + 0.055), 2.4); return x < 0.04045f ? r1 : r2; } static float frgb2std(float x) { float r1, r2; r1 = x * 12.92f; r2 = 1.055 * pow(x, 1 / 2.4) - 0.055; return x < 0.0031308f ? r1 : r2; } /** * Converts 8-bit RGB samples to floating point. */ static void rgb2float(unsigned n, float *f, const unsigned char *u) { unsigned i; for (i = 0; i < n; ++i) f[i] = u[i]; for (i = 0; i < n; ++i) f[i] /= 255; } /** * Converts floating point RGB samples to 8-bit. */ static void float2rgb(unsigned n, unsigned char *u, float *f) { unsigned i; for (i = 0; i < n; ++i) f[i] *= 256; for (i = 0; i < n; ++i) f[i] = roundf(f[i]); for (i = 0; i < n; ++i) u[i] = MAX(0, MIN(255, f[i])); } /** * Converts standard RGB to linear RGB. * * This makes subtraction look good by flattening out the bias curve * that PC display manufacturers like to use. */ static dontinline void rgb2lin(unsigned n, float *f, const unsigned char *u) { unsigned i; rgb2float(n, f, u); for (i = 0; i < n; ++i) f[i] = frgb2lin(f[i]); } /** * Converts linear RGB to standard RGB. */ static dontinline void rgb2std(unsigned n, unsigned char *u, float *f) { unsigned i; for (i = 0; i < n; ++i) f[i] = frgb2std(f[i]); float2rgb(n, u, f); } /*───────────────────────────────────────────────────────────────────────────│─╗ │ derasterize § blocks ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ struct Cell { char16_t rune; unsigned char bg[CN], fg[CN]; }; /** * Serializes ANSI background, foreground, and UNICODE glyph to wire. */ static char *celltoa(char *p, struct Cell cell) { *p++ = 033; *p++ = '['; *p++ = '4'; *p++ = '8'; *p++ = ';'; *p++ = '2'; *p++ = ';'; p = itoa8(p, cell.bg[0]); *p++ = ';'; p = itoa8(p, cell.bg[1]); *p++ = ';'; p = itoa8(p, cell.bg[2]); *p++ = ';'; *p++ = '3'; *p++ = '8'; *p++ = ';'; *p++ = '2'; *p++ = ';'; p = itoa8(p, cell.fg[0]); *p++ = ';'; p = itoa8(p, cell.fg[1]); *p++ = ';'; p = itoa8(p, cell.fg[2]); *p++ = 'm'; p = tptoa(p, cell.rune); return p; } /** * Picks ≤2**MC unique (bg,fg) pairs from product of lb. */ static unsigned combinecolors(unsigned char bf[1u << MC][2], const unsigned char bl[CN][YS * XS]) { uint64_t hv, ht[(1u << MC) * 2]; unsigned i, j, n, b, f, h, hi, bu, fu; bzero(ht, sizeof(ht)); for (n = b = 0; b < BN && n < (1u << MC); ++b) { bu = bl[2][b] << 020 | bl[1][b] << 010 | bl[0][b]; hi = 0; hi = (((bu >> 000) & 0xff) + hi) * PHIPRIME; hi = (((bu >> 010) & 0xff) + hi) * PHIPRIME; hi = (((bu >> 020) & 0xff) + hi) * PHIPRIME; for (f = b + 1; f < BN && n < (1u << MC); ++f) { fu = bl[2][f] << 020 | bl[1][f] << 010 | bl[0][f]; h = hi; h = (((fu >> 000) & 0xff) + h) * PHIPRIME; h = (((fu >> 010) & 0xff) + h) * PHIPRIME; h = (((fu >> 020) & 0xff) + h) * PHIPRIME; h = h & 0xffff; h = MAX(1, h); hv = 0; hv <<= 030; hv |= fu; hv <<= 030; hv |= bu; hv <<= 020; hv |= h; for (i = 0;; ++i) { j = (h + i * (i + 1) / 2) & (ARRAYLEN(ht) - 1); if (!ht[j]) { ht[j] = hv; bf[n][0] = b; bf[n][1] = f; n++; break; } else if (ht[j] == hv) { break; } } } } return n; } /** * Computes distance between synthetic block and actual. */ #define ADJUDICATE(SYMBOL, ARCH) \ ARCH static float SYMBOL(unsigned b, unsigned f, unsigned g, \ const float lb[CN][YS * XS]) { \ unsigned i, k, gu; \ float p[BN], q[BN], fu, bu, r; \ bzero(q, sizeof(q)); \ for (k = 0; k < CN; ++k) { \ gu = kGlyphs[g]; \ bu = lb[k][b]; \ fu = lb[k][f]; \ for (i = 0; i < BN; ++i) p[i] = (gu & (1u << i)) ? fu : bu; \ for (i = 0; i < BN; ++i) p[i] -= lb[k][i]; \ for (i = 0; i < BN; ++i) p[i] *= p[i]; \ for (i = 0; i < BN; ++i) q[i] += p[i]; \ } \ r = 0; \ for (i = 0; i < BN; ++i) q[i] = sqrtf(q[i]); \ for (i = 0; i < BN; ++i) r += q[i]; \ return r; \ } ADJUDICATE(adjudicate_avx2, microarchitecture("avx2,fma")) ADJUDICATE(adjudicate_avx, microarchitecture("avx")) ADJUDICATE(adjudicate_default, ) static float (*adjudicate_hook)(unsigned, unsigned, unsigned, const float[CN][YS * XS]); static float adjudicate2(unsigned b, unsigned f, unsigned g, const float lb[CN][YS * XS]) { if (!adjudicate_hook) { if (X86_HAVE(AVX2) && X86_HAVE(FMA)) { adjudicate_hook = adjudicate_avx2; } else if (X86_HAVE(AVX)) { adjudicate_hook = adjudicate_avx; } else { adjudicate_hook = adjudicate_default; } } return adjudicate_hook(b, f, g, lb); } static float adjudicate(unsigned b, unsigned f, unsigned g, const float lb[CN][YS * XS]) { unsigned i, k, gu; float p[BN], q[BN], fu, bu, r; bzero(q, sizeof(q)); for (k = 0; k < CN; ++k) { gu = kGlyphs[g]; bu = lb[k][b]; fu = lb[k][f]; for (i = 0; i < BN; ++i) p[i] = (gu & (1u << i)) ? fu : bu; for (i = 0; i < BN; ++i) p[i] -= lb[k][i]; for (i = 0; i < BN; ++i) p[i] *= p[i]; for (i = 0; i < BN; ++i) q[i] += p[i]; } r = 0; for (i = 0; i < BN; ++i) q[i] = sqrtf(q[i]); for (i = 0; i < BN; ++i) r += q[i]; return r; } /** * Converts tiny bitmap graphic into unicode glyph. */ static struct Cell derasterize(unsigned char block[CN][YS * XS]) { struct Cell cell; unsigned i, n, b, f, g; float r, best, lb[CN][YS * XS]; unsigned char bf[1u << MC][2]; rgb2lin(CN * YS * XS, lb[0], block[0]); n = combinecolors(bf, block); best = FLT_MAX; cell.rune = 0; for (i = 0; i < n; ++i) { b = bf[i][0]; f = bf[i][1]; for (g = 0; g < GN; ++g) { r = adjudicate(b, f, g, lb); if (r < best) { best = r; cell.rune = kRunes[g]; cell.bg[0] = block[0][b]; cell.bg[1] = block[1][b]; cell.bg[2] = block[2][b]; cell.fg[0] = block[0][f]; cell.fg[1] = block[1][f]; cell.fg[2] = block[2][f]; if (!r) return cell; } } } return cell; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ derasterize § graphics ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ /** * Turns packed 8-bit RGB graphic into ANSI UNICODE text. */ static char *RenderImage(char *v, unsigned yn, unsigned xn, const unsigned char srgb[yn][YS][xn][XS][CN]) { unsigned y, x, i, j, k; unsigned char copy[YS][XS][CN] forcealign(32); unsigned char block[CN][YS * XS] forcealign(32); DCHECK_ALIGNED(32, v); DCHECK_ALIGNED(32, srgb); for (y = 0; y < yn; ++y) { if (y) { *v++ = 033; *v++ = '['; *v++ = '0'; *v++ = 'm'; *v++ = '\n'; } for (x = 0; x < xn; ++x) { for (i = 0; i < YS; ++i) { memcpy(copy[i], srgb[y][i][x], XS * CN); } for (i = 0; i < YS; ++i) { for (j = 0; j < XS; ++j) { for (k = 0; k < CN; ++k) { block[k][i * XS + j] = copy[i][j][k]; } } } v = celltoa(v, derasterize(block)); } } return v; } /*───────────────────────────────────────────────────────────────────────────│─╗ │ derasterize § systems ─╬─│┼ ╚────────────────────────────────────────────────────────────────────────────│*/ static void PrintImage(unsigned yn, unsigned xn, const unsigned char rgb[yn][YS][xn][XS][CN]) { size_t size; char *v, *vt; size = yn * (xn * (32 + (2 + (1 + 3) * 3) * 2 + 1 + 3)) * 1 + 5 + 1; size = ROUNDUP(size, FRAMESIZE); CHECK_NOTNULL((vt = _mapanon(size))); v = RenderImage(vt, yn, xn, rgb); *v++ = '\r'; *v++ = 033; *v++ = '['; *v++ = '0'; *v++ = 'm'; CHECK_NE(-1, xwrite(1, vt, v - vt)); CHECK_NE(-1, munmap(vt, size)); } /** * Determines dimensions of teletypewriter. */ static void GetTermSize(unsigned out_rows[1], unsigned out_cols[1]) { struct winsize ws; ws.ws_row = 24; ws.ws_col = 80; if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) { ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws); } out_rows[0] = ws.ws_row; out_cols[0] = ws.ws_col; } static int ReadAll(int fd, void *data, size_t size) { char *p; ssize_t rc; size_t got, n; p = data; n = size; do { if ((rc = read(fd, p, n)) == -1) return -1; got = rc; assert(got || !n); p += got; n -= got; } while (n); return 0; } /** * Loads and scales image via ImageMagick `convert` command. * * @param path is filename of graphic * @param yn is desired height * @param xn is desired width * @param rgb is memory allocated by caller for image */ static void LoadFileViaImageMagick(const char *path, unsigned yn, unsigned xn, unsigned char rgb[yn][YS][xn][XS][CN]) { const char *convert; int pid, ws, pipefds[2]; char pathbuf[PATH_MAX], dim[32]; if (!(convert = commandv("convert", pathbuf, sizeof(pathbuf)))) { fputs("error: `convert` command not found\n" "try: apt-get install imagemagick\n", stderr); exit(EXIT_FAILURE); } sprintf(dim, "%ux%u!", xn * XS, yn * YS); CHECK_NE(-1, pipe2(pipefds, O_CLOEXEC)); if (!(pid = vfork())) { dup2(pipefds[1], 1); execv(convert, (char *const[]){"convert", path, "-resize", dim, "-depth", "8", "-colorspace", "sRGB", "rgb:-", NULL}); abort(); } CHECK_NE(-1, close(pipefds[1])); CHECK_NE(-1, ReadAll(pipefds[0], rgb, yn * YS * xn * XS * CN)); CHECK_NE(-1, close(pipefds[0])); CHECK_NE(-1, waitpid(pid, &ws, 0)); CHECK_EQ(0, WEXITSTATUS(ws)); } static void LoadFile(const char *path, size_t yn, size_t xn, void *rgb) { struct stat st; size_t data2size, data3size; void *map, *data, *data2, *data3; int fd, gotx, goty, channels_in_file; CHECK_NE(-1, (fd = open(path, O_RDONLY)), "%s", path); CHECK_NE(-1, fstat(fd, &st)); CHECK_GT(st.st_size, 0); CHECK_LE(st.st_size, INT_MAX); /* LOGIFNEG1(fadvise(fd, 0, 0, MADV_WILLNEED | MADV_SEQUENTIAL)); */ CHECK_NE(MAP_FAILED, (map = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))); CHECK_NOTNULL((data = stbi_load_from_memory(map, st.st_size, &gotx, &goty, &channels_in_file, CN)), "%s", path); CHECK_NE(-1, munmap(map, st.st_size)); CHECK_NE(-1, close(fd)); #if 1 stbir_resize_uint8(data, gotx, goty, 0, rgb, xn * XS, yn * YS, 0, CN); #else CHECK_EQ(CN, 3); data2size = ROUNDUP(sizeof(float) * goty * gotx * CN, FRAMESIZE); data3size = ROUNDUP(sizeof(float) * yn * YS * xn * XS * CN, FRAMESIZE); CHECK_NOTNULL((data2 = _mapanon(data2size))); CHECK_NOTNULL((data3 = _mapanon(data3size))); rgb2lin(goty * gotx * CN, data2, data); lanczos3(yn * YS, xn * XS, data3, goty, gotx, data2, gotx * 3); rgb2std(yn * YS * xn * XS * CN, rgb, data3); CHECK_NE(-1, munmap(data2, data2size)); CHECK_NE(-1, munmap(data3, data3size)); #endif free(data); } static int ParseNumberOption(const char *arg) { long x; x = strtol(arg, NULL, 0); if (!(1 <= x && x <= INT_MAX)) { fprintf(stderr, "invalid flexidecimal: %s\n\n", arg); exit(EXIT_FAILURE); } return x; } static void PrintUsage(int rc, FILE *f) { fputs(HELPTEXT, f); exit(rc); } static void GetOpts(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "?Hmx:y:w:h:")) != -1) { switch (opt) { case 'w': case 'x': x_ = ParseNumberOption(optarg); break; case 'h': case 'y': y_ = ParseNumberOption(optarg); break; case 'm': m_ = 1; break; case '?': case 'H': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } } int main(int argc, char *argv[]) { int i; void *rgb; size_t size; char *option; unsigned yd, xd; ShowCrashReports(); GetOpts(argc, argv); // if sizes are given, 2 cases: // - positive values: use that as the target size // - negative values: add, for ex to offset the command prompt size GetTermSize(&yd, &xd); if (y_ <= 0) { y_ += yd; } if (x_ <= 0) { x_ += xd; } // FIXME: on the conversion stage should do 2Y because of halfblocks // printf( "filename >%s<\tx >%d<\ty >%d<\n\n", filename, x_, y_); size = y_ * YS * x_ * XS * CN; CHECK_NOTNULL((rgb = _mapanon(ROUNDUP(size, FRAMESIZE)))); for (i = optind; i < argc; ++i) { if (!argv[i]) continue; if (m_) { LoadFileViaImageMagick(argv[i], y_, x_, rgb); } else { LoadFile(argv[i], y_, x_, rgb); } PrintImage(y_, x_, rgb); } munmap(rgb, ROUNDUP(size, FRAMESIZE)); return 0; } #endif /* __x86_64__ */
21,122
622
jart/cosmopolitan
false
cosmopolitan/tool/viz/basicidea.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 "dsp/scale/scale.h" #include "libc/calls/calls.h" #include "libc/calls/ioctl.h" #include "libc/calls/struct/stat.h" #include "libc/calls/struct/winsize.h" #include "libc/fmt/fmt.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/str/locale.h" #include "libc/str/str.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/termios.h" #include "third_party/stb/stb_image.h" #define SQR(X) ((X) * (X)) #define UNCUBE(x) x < 48 ? 0 : x < 115 ? 1 : (x - 35) / 40 #define ORDIE(X) \ do { \ if (!(X)) perror(#X), exit(1); \ } while (0) int want24bit_; int wantfullsize_; /** * Quantizes 24-bit RGB to xterm256 code range [16,256). */ int rgb2xterm256(int r, int g, int b) { unsigned char cube[] = {0, 0137, 0207, 0257, 0327, 0377}; int av, ir, ig, ib, il, qr, qg, qb, ql; av = r * .299 + g * .587 + b * .114 + .5; ql = (il = av > 238 ? 23 : (av - 3) / 10) * 10 + 8; qr = cube[(ir = UNCUBE(r))]; qg = cube[(ig = UNCUBE(g))]; qb = cube[(ib = UNCUBE(b))]; if (SQR(qr - r) + SQR(qg - g) + SQR(qb - b) <= SQR(ql - r) + SQR(ql - g) + SQR(ql - b)) { return ir * 36 + ig * 6 + ib + 020; } else { return il + 0350; } } /** * Prints raw packed 8-bit RGB data from memory. */ void PrintImage(int yn, int xn, unsigned char rgb[yn][xn][3]) { unsigned y, x; for (y = 0; y < yn; y += 2) { for (x = 0; x < xn; ++x) { if (want24bit_) { printf("\033[48;2;%hhu;%hhu;%hhu;38;2;%hhu;%hhu;%hhum▄", rgb[y + 0][x][0], rgb[y + 0][x][1], rgb[y + 0][x][2], rgb[MIN(y + 1, yn - 1)][x][0], rgb[MIN(y + 1, yn - 1)][x][1], rgb[MIN(y + 1, yn - 1)][x][2]); } else { printf( "\033[48;5;%hhu;38;5;%hhum▄", rgb2xterm256(rgb[y + 0][x][0], rgb[y + 0][x][1], rgb[y + 0][x][2]), rgb2xterm256(rgb[MIN(y + 1, yn - 1)][x][0], rgb[MIN(y + 1, yn - 1)][x][1], rgb[MIN(y + 1, yn - 1)][x][2])); } } printf("\e[0m\n"); } } /** * Determines dimensions of teletypewriter. */ void GetTermSize(int *out_rows, int *out_cols) { struct winsize ws; ws.ws_row = 20; ws.ws_col = 80; ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws); ioctl(STDIN_FILENO, TIOCGWINSZ, &ws); *out_rows = ws.ws_row; *out_cols = ws.ws_col; } void ReadAll(int fd, char *p, size_t n) { ssize_t rc; size_t got; do { ORDIE((rc = read(fd, p, n)) != -1); got = rc; if (!got && n) { fprintf(stderr, "error: expected eof\n"); exit(EXIT_FAILURE); } p += got; n -= got; } while (n); } static void Deblinterlace(long zn, long yn, long xn, unsigned char dst[zn][yn][xn], const unsigned char src[yn][xn][zn]) { long y, x, z; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { for (z = 0; z < zn; ++z) { dst[z][y][x] = src[y][x][z]; } } } } static void Reblinterlace(long zn, long yn, long xn, unsigned char dst[yn][xn][zn], const unsigned char src[zn][yn][xn]) { long y, x, z; for (y = 0; y < yn; ++y) { for (x = 0; x < xn; ++x) { for (z = 0; z < zn; ++z) { dst[y][x][z] = src[z][y][x]; } } } } int main(int argc, char *argv[]) { struct stat st; void *map, *data, *data2; int i, fd, tyn, txn, yn, xn, cn; setlocale(LC_ALL, "C.UTF-8"); for (i = 1; i < argc; ++i) { if (strcmp(argv[i], "-t") == 0) { want24bit_ = 1; } else if (strcmp(argv[i], "-f") == 0) { wantfullsize_ = 1; } else { fd = open(argv[i], O_RDONLY); if (fd == -1) { perror(argv[i]); exit(1); } fstat(fd, &st); map = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); data = stbi_load_from_memory(map, st.st_size, &xn, &yn, &cn, 3); munmap(map, st.st_size); close(fd); if (!wantfullsize_) { GetTermSize(&tyn, &txn); --tyn; tyn *= 2; data2 = memalign(32, 3 * yn * xn); Deblinterlace(3, yn, xn, data2, data); free(data); data = memalign(32, 3 * tyn * txn); EzGyarados(3, tyn, txn, data, 3, yn, xn, data2, 0, 3, tyn, txn, yn, xn, 0, 0, 0, 0); free(data2); data2 = memalign(32, 3 * yn * xn); Reblinterlace(3, tyn, txn, data2, data); free(data); data = data2; yn = tyn; xn = txn; } PrintImage(yn, xn, data); free(data); } } return 0; }
6,654
192
jart/cosmopolitan
false
cosmopolitan/tool/viz/xterm256effective2.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 "dsp/tty/quant.h" #include "libc/fmt/fmt.h" #include "libc/log/check.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" #define USAGE \ " [FLAGS] [PATH...]\n\ \n\ Flags:\n\ -o PATH output path\n\ -h shows this information\n\ \n" static size_t linecap_; static FILE *in_, *out_; static char *inpath_, *outpath_, *line_; void PrintUsage(int rc, FILE *f) { fputs("Usage: ", f); fputs(program_invocation_name, f); fputs(USAGE, f); exit(rc); } void GetOpts(int *argc, char *argv[]) { int opt; outpath_ = "-"; while ((opt = getopt(*argc, argv, "?ho:")) != -1) { switch (opt) { case 'o': outpath_ = optarg; break; case '?': case 'h': PrintUsage(EXIT_SUCCESS, stdout); default: PrintUsage(EX_USAGE, stderr); } } if (optind == *argc) { argv[(*argc)++] = "-"; } } #define U256F1(X) ((float)((X)&0xffu) * 256.0f) #define F1U256(X) MAX(MIN((int)rintl(roundl(256.0f * (X))), 255), 0) forceinline struct TtyRgb getquant(unsigned xt) { return g_ansi2rgb_[xt]; } forceinline unsigned dist(int x, int y) { return x - y; } forceinline unsigned sqr(int x) { return x * x; } static unsigned rgb2hsl(unsigned rgba) { /* this is broken */ unsigned h8, s8, l8; float r, g, b, h, s, d, l, cmax, cmin; r = U256F1(rgba); g = U256F1(rgba >> 010); b = U256F1(rgba >> 020); cmax = MAX(MAX(r, g), b); cmin = MIN(MIN(r, g), b); h = 0.0f; s = 0.0f; d = cmax - cmin; l = (cmax + cmin) / 2.0f; if (cmax != cmin) { s = l > 0.5L ? d / (2.0f - cmax - cmin) : d / (cmax + cmin); if (cmax == r) { h = (g - b) / d + (g < b ? 6.0f : 0.0f); } else if (cmax == g) { h = (b - r) / d + 2.0f; } else if (cmax == b) { h = (r - g) / d + 4.0f; } h /= 6.0f; } h8 = F1U256(h); s8 = F1U256(s); l8 = F1U256(l); return ((rgba >> 030) & 255) << 030 | l8 << 020 | s8 << 010 | h8; } static struct TtyRgb rgb2hsl2(struct TtyRgb rgb) { unsigned x = (unsigned)rgb.b << 020 | (unsigned)rgb.g << 010 | (unsigned)rgb.r; unsigned y = rgb2hsl(x); return (struct TtyRgb){ .r = y & 0xff, .g = (y >> 010) & 0xff, .b = (y >> 020) & 0xff}; } static unsigned rgbdist(struct TtyRgb x, struct TtyRgb y) { x = rgb2hsl2(x); y = rgb2hsl2(y); return sqrt(sqr(dist(x.r, y.r)) + sqr(dist(x.g, y.g)) + sqr(dist(x.b, y.b))); } static unsigned xtdist(unsigned x, unsigned y) { return rgbdist(getquant(x), getquant(y)); } void Show(unsigned color, unsigned bg, unsigned fg, unsigned glyph) { uint8_t r, g, b; b = (color >> 020) & 0xff; g = (color >> 010) & 0xff; r = color & 0xff; printf("\tmix\t0x%04x,%3d,%3d,%3d,%3d,%3d,%3d\t# \e[48;2;%d;%d;%dm \e[0m\n", rgbdist((struct TtyRgb){r, g, b, 0}, (struct TtyRgb){0, 0, 0, 0}), r, g, b, bg, fg, glyph, r, g, b); } void ProcessFile(void) { char *p; unsigned color1, bg1, fg1, glyph1; unsigned color, bg, fg, glyph; color1 = -1u; bg1 = -1u; fg1 = -1u; glyph1 = -1u; while ((getline(&line_, &linecap_, in_)) != -1) { p = _chomp(line_); sscanf(p, "%x, %u,%u,%u", &color, &bg, &fg, &glyph); if (color != color1) { if (color1 != -1u) { Show(color1, bg1, fg1, glyph1); } color1 = color; bg1 = bg; fg1 = fg; glyph1 = glyph; } if ((fg1 && !fg) || (fg && fg1 && xtdist(fg, bg) < xtdist(fg1, bg1))) { color1 = color; bg1 = bg; fg1 = fg; glyph1 = glyph; } } Show(color1, bg1, fg1, glyph1); } int main(int argc, char *argv[]) { size_t i; GetOpts(&argc, argv); CHECK_NOTNULL((out_ = fopen(outpath_, "w"))); for (i = optind; i < argc; ++i) { CHECK_NOTNULL((in_ = fopen((inpath_ = argv[i]), "r"))); ProcessFile(); CHECK_NE(-1, fclose(in_)); in_ = 0; } CHECK_NE(-1, fclose(out_)); out_ = 0; free(line_); return 0; }
5,944
187
jart/cosmopolitan
false
cosmopolitan/tool/viz/invertblocks.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/log/check.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "third_party/getopt/getopt.h" static FILE *fi_, *fo_; static char *inpath_, *outpath_; wontreturn void usage(int rc, FILE *f) { fprintf(f, "%s%s%s\n", "Usage: ", program_invocation_name, " [-o FILE] [FILE...]\n"); exit(rc); } void getopts(int *argc, char *argv[]) { int opt; outpath_ = "-"; while ((opt = getopt(*argc, argv, "?ho:")) != -1) { switch (opt) { case 'o': outpath_ = optarg; break; case '?': case 'h': usage(EXIT_SUCCESS, stdout); default: usage(EX_USAGE, stderr); } } if (optind == *argc) { argv[(*argc)++] = "-"; } } void processfile(void) { wint_t wc; while ((wc = fgetwc(fi_)) != -1) { switch (wc) { case L'█': wc = L' '; break; case L'▓': wc = L'░'; break; case L'▒': wc = L'▒'; break; case L'░': wc = L'▓'; break; /* █ */ case L'▐': wc = L'▌'; break; case L'▌': wc = L'▐'; break; case L'▀': wc = L'▄'; break; case L'▄': wc = L'▀'; break; case L'☺': wc = L'☻'; break; case L'☻': wc = L'☺'; break; case L'○': wc = L'◙'; break; case L'◙': wc = L'○'; break; default: break; } fputwc(wc, fo_); } } int main(int argc, char *argv[]) { size_t i; getopts(&argc, argv); CHECK_NOTNULL((fo_ = fopen(outpath_, "w"))); for (i = optind; i < argc; ++i) { CHECK_NOTNULL((fi_ = fopen((inpath_ = argv[i]), "r"))); processfile(); CHECK_NE(-1, fclose(fi_)); fi_ = 0; } CHECK_NE(-1, fclose(fo_)); fo_ = 0; return 0; }
3,802
117
jart/cosmopolitan
false
cosmopolitan/tool/viz/bing.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/calls/calls.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/str/tab.internal.h" #include "libc/sysv/consts/ex.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/fileno.h" #include "third_party/getopt/getopt.h" /** * @fileoverview Bing: Binary → Glyphs. * Intended for oldskool data science. */ int ispipe_; int newlines_; wontreturn void ShowUsage(FILE *f, int rc) { fputs(program_invocation_name, f); fputs(": [-p] [-n] [FILE...]\n", f); exit(rc); } void GetOpts(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hpn")) != -1) { switch (opt) { case 'p': ispipe_ = true; break; case 'n': newlines_ = true; break; case 'h': ShowUsage(stdout, EXIT_SUCCESS); default: ShowUsage(stderr, EX_USAGE); } } } void bing(FILE *f) { int c, c2; while ((c = fgetc(f)) != -1) { c2 = c == '\n' && newlines_ ? '\n' : kCp437[c & 0xff]; if (ispipe_) { fputc(c, stdout); fputwc(c2, stderr); } else { fputwc(c2, stdout); } } fputc('\n', ispipe_ ? stderr : stdout); } int main(int argc, char *argv[]) { FILE *f; size_t i; GetOpts(argc, argv); if (optind < argc) { for (i = optind; i < argc; ++i) { if (!(f = fopen(argv[i], "rb"))) { perror(argv[i]); exit(EXIT_FAILURE); } bing(f); fclose(f); } } else { bing(stdin); } return 0; }
3,389
94
jart/cosmopolitan
false
cosmopolitan/tool/viz/fixconsole.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/dce.h" #include "libc/intrin/kprintf.h" #include "libc/nt/console.h" #include "libc/nt/enum/consolemodeflags.h" #include "libc/nt/runtime.h" #include "libc/runtime/runtime.h" int main(int argc, char *argv[]) { if (!IsWindows()) { kprintf("%s is intended for windows%n", argv[0]); return 1; } SetConsoleMode(GetStdHandle(kNtStdInputHandle), kNtEnableProcessedInput | kNtEnableLineInput | kNtEnableEchoInput | kNtEnableMouseInput | kNtEnableInsertMode | kNtEnableQuickEditMode | kNtEnableExtendedFlags | kNtEnableAutoPosition); SetConsoleMode(GetStdHandle(kNtStdOutputHandle), kNtEnableProcessedOutput | kNtEnableWrapAtEolOutput); SetConsoleMode(GetStdHandle(kNtStdErrorHandle), kNtEnableProcessedOutput | kNtEnableWrapAtEolOutput | kNtEnableVirtualTerminalProcessing); _Exit(0); }
2,787
43
jart/cosmopolitan
false
cosmopolitan/tool/viz/unicode.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/str/unicode.h" #include "libc/fmt/fmt.h" #include "libc/mem/gc.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/x/xasprintf.h" int a, b, w, i; char name[512]; void DisplayUnicodeCharacter(void) { int c, cw; c = i; cw = wcwidth(c); if (cw < 1) { c = '?'; cw = 1; } if (w) { if (w + 1 + cw > 80) { printf("\n"); w = 0; } else { fputc(' ', stdout); w += 1 + cw; } } if (!w) { printf("%08x ", i); w = 9 + cw; } fputwc(c, stdout); } void DisplayUnicodeBlock(void) { if (a == 0x10000) { printf("\n\n\n\n\n\n\n " "ASTRAL PLANES\n\n\n\n\n"); } if (a == 0x0590 /* hebrew */) return; if (a == 0x0600 /* arabic */) return; if (a == 0x08a0 /* arabic */) return; if (a == 0x0750 /* arabic */) return; if (a == 0x0700 /* syriac */) return; if (a == 0x10800 /* cypriot */) return; printf("\n\n%-60s%20s\n" "──────────────────────────────────────────────" "──────────────────────────────────\n", name, _gc(xasprintf("%04x .. %04x", a, b))); w = 0; for (i = a; i <= b; ++i) { DisplayUnicodeCharacter(); } } int main(int argc, char *argv[]) { FILE *f; char *line; size_t linesize; printf("\n\n\n\n\n UNICODE PLANES\n\n\n\n"); f = fopen("libc/str/blocks.txt", "r"); line = NULL; linesize = 0; while (!feof(f)) { if (getline(&line, &linesize, f) == -1) break; if (sscanf(line, "%x..%x; %s", &a, &b, name) != 3) continue; DisplayUnicodeBlock(); } free(line); fclose(f); return 0; }
3,667
92
jart/cosmopolitan
false
cosmopolitan/tool/viz/virtualquery.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/dce.h" #include "libc/fmt/conv.h" #include "libc/intrin/describeflags.internal.h" #include "libc/macros.internal.h" #include "libc/nt/enum/memflags.h" #include "libc/nt/memory.h" #include "libc/nt/struct/memorybasicinformation.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" /** * @fileoverview WIN32 Virtual Memory Layout Dump Utility */ static const struct DescribeFlags kNtMemState[] = { {kNtMemCommit, "Commit"}, // {kNtMemFree, "Free"}, // {kNtMemReserve, "Reserve"}, // }; const char *DescribeNtMemState(char buf[64], uint32_t x) { return DescribeFlags(buf, 64, kNtMemState, ARRAYLEN(kNtMemState), "kNtMem", x); } static const struct DescribeFlags kNtMemType[] = { {kNtMemImage, "Image"}, // {kNtMemMapped, "Mapped"}, // {kNtMemPrivate, "Private"}, // }; const char *DescribeNtMemType(char buf[64], uint32_t x) { return DescribeFlags(buf, 64, kNtMemType, ARRAYLEN(kNtMemType), "kNtMem", x); } int main(int argc, char *argv[]) { char *p, b[5][64]; struct NtMemoryBasicInformation mi; if (!IsWindows()) { fprintf(stderr, "error: %s is intended for windows\n", program_invocation_short_name); exit(1); } printf("%-12s %-12s %10s %16s %16s %32s %32s\n", "Allocation", "BaseAddress", "RegionSize", "State", "Type", "AllocationProtect", "Protect"); for (p = 0;; p = (char *)mi.BaseAddress + mi.RegionSize) { bzero(&mi, sizeof(mi)); if (!VirtualQuery(p, &mi, sizeof(mi))) break; sizefmt(b[0], mi.RegionSize, 1024); printf("%.12lx %.12lx %10s %16s %16s %32s %32s\n", mi.AllocationBase, mi.BaseAddress, b[0], DescribeNtMemState(b[1], mi.State), DescribeNtMemType(b[2], mi.Type), (DescribeNtPageFlags)(b[3], mi.AllocationProtect), (DescribeNtPageFlags)(b[4], mi.Protect)); } }
3,751
76
jart/cosmopolitan
false
cosmopolitan/tool/viz/ntmaster.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 "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/x/xgetline.h" #define DLL "iphlpapi" /** * @fileoverview Tool for adding rnew libraries to libc/nt/master.sh * * If provided with a /tmp/syms.txt file containing one symbol name per * line, this tool will output the correctly tab indented shell code. */ int main(int argc, char *argv[]) { FILE *f; int i, n, t; char *sym, tabs[64]; ShowCrashReports(); f = fopen("/tmp/syms.txt", "r"); memset(tabs, '\t', 64); while ((sym = _chomp(xgetline(f)))) { if (strlen(sym)) { printf("imp\t"); /* what we call the symbol */ i = printf("'%s'", sym); t = 0; n = 56; if (i % 8) ++t, i = ROUNDUP(i, 8); t += (n - i) / 8; printf("%.*s", t, tabs); /* what the kernel dll calls the symbol */ i = printf("%s", sym); t = 0; n = 56; if (i % 8) ++t, i = ROUNDUP(i, 8); t += (n - i) / 8; printf("%.*s", t, tabs); /* dll short name */ i = printf("%s", DLL); t = 0; n = 16; if (i % 8) ++t, i = ROUNDUP(i, 8); t += (n - i) / 8; printf("%.*s", t, tabs); /* hint */ i = printf("0"); t = 0; n = 8; if (i % 8) ++t, i = ROUNDUP(i, 8); t += (n - i) / 8; printf("%.*s", t, tabs); printf("\n"); } free(sym); } return 0; }
3,304
84
jart/cosmopolitan
false
cosmopolitan/tool/viz/viz.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_VIZ TOOL_VIZ_SRCS := $(wildcard tool/viz/*.c) TOOL_VIZ_OBJS = \ $(TOOL_VIZ_SRCS:%.c=o/$(MODE)/%.o) TOOL_VIZ_COMS = \ $(TOOL_VIZ_SRCS:%.c=o/$(MODE)/%.com) TOOL_VIZ_BINS = \ $(TOOL_VIZ_COMS) \ $(TOOL_VIZ_COMS:%=%.dbg) TOOL_VIZ_DIRECTDEPS = \ DSP_CORE \ DSP_MPEG \ DSP_SCALE \ DSP_TTY \ LIBC_CALLS \ LIBC_DNS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_COMDLG32 \ LIBC_NT_GDI32 \ LIBC_NT_KERNEL32 \ LIBC_NT_USER32 \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_X \ LIBC_ZIPOS \ NET_HTTP \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_DLMALLOC \ THIRD_PARTY_GDTOA \ THIRD_PARTY_GETOPT \ THIRD_PARTY_MAXMIND \ THIRD_PARTY_MUSL \ THIRD_PARTY_STB \ THIRD_PARTY_XED \ THIRD_PARTY_ZLIB \ TOOL_DECODE_LIB \ TOOL_VIZ_LIB TOOL_VIZ_DEPS := \ $(call uniq,$(foreach x,$(TOOL_VIZ_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/viz/viz.pkg: \ $(TOOL_VIZ_OBJS) \ $(foreach x,$(TOOL_VIZ_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/viz/%.com.dbg: \ $(TOOL_VIZ_DEPS) \ o/$(MODE)/tool/viz/%.o \ o/$(MODE)/tool/viz/viz.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/viz/printimage.com.dbg: \ $(TOOL_VIZ_DEPS) \ o/$(MODE)/tool/viz/printimage.o \ o/$(MODE)/tool/viz/viz.pkg \ o/$(MODE)/LICENSE.zip.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/viz/printimage.com: \ o/$(MODE)/tool/viz/printimage.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) o/$(MODE)/tool/viz/printvideo.com: \ o/$(MODE)/tool/viz/printvideo.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) o/$(MODE)/tool/viz/derasterize.o: private \ OVERRIDE_CFLAGS += \ -DSTACK_FRAME_UNLIMITED \ $(MATHEMATICAL) o/$(MODE)/tool/viz/magikarp.o: private \ OVERRIDE_CFLAGS += \ $(MATHEMATICAL) $(TOOL_VIZ_OBJS): \ $(BUILD_FILES) \ tool/viz/viz.mk .PHONY: o/$(MODE)/tool/viz o/$(MODE)/tool/viz: \ o/$(MODE)/tool/viz/lib \ $(TOOL_VIZ_BINS) \ $(TOOL_VIZ_CHECKS)
2,610
118
jart/cosmopolitan
false