Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/dwarf/call_frame.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>dwarf/call_frame.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-kw">const</span> builtin = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;builtin&quot;</span>);</span> <span class="line" id="L2"><span class="tok-kw">const</span> std = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;../std.zig&quot;</span>);</span> <span class="line" id="L3"><span class="tok-kw">const</span> mem = std.mem;</span> <span class="line" id="L4"><span class="tok-kw">const</span> debug = std.debug;</span> <span class="line" id="L5"><span class="tok-kw">const</span> leb = std.leb;</span> <span class="line" id="L6"><span class="tok-kw">const</span> dwarf = std.dwarf;</span> <span class="line" id="L7"><span class="tok-kw">const</span> abi = dwarf.abi;</span> <span class="line" id="L8"><span class="tok-kw">const</span> expressions = dwarf.expressions;</span> <span class="line" id="L9"><span class="tok-kw">const</span> assert = std.debug.assert;</span> <span class="line" id="L10"></span> <span class="line" id="L11"><span class="tok-kw">const</span> Opcode = <span class="tok-kw">enum</span>(<span class="tok-type">u8</span>) {</span> <span class="line" id="L12"> advance_loc = <span class="tok-number">0x1</span> &lt;&lt; <span class="tok-number">6</span>,</span> <span class="line" id="L13"> offset = <span class="tok-number">0x2</span> &lt;&lt; <span class="tok-number">6</span>,</span> <span class="line" id="L14"> restore = <span class="tok-number">0x3</span> &lt;&lt; <span class="tok-number">6</span>,</span> <span class="line" id="L15"></span> <span class="line" id="L16"> nop = <span class="tok-number">0x00</span>,</span> <span class="line" id="L17"> set_loc = <span class="tok-number">0x01</span>,</span> <span class="line" id="L18"> advance_loc1 = <span class="tok-number">0x02</span>,</span> <span class="line" id="L19"> advance_loc2 = <span class="tok-number">0x03</span>,</span> <span class="line" id="L20"> advance_loc4 = <span class="tok-number">0x04</span>,</span> <span class="line" id="L21"> offset_extended = <span class="tok-number">0x05</span>,</span> <span class="line" id="L22"> restore_extended = <span class="tok-number">0x06</span>,</span> <span class="line" id="L23"> <span class="tok-null">undefined</span> = <span class="tok-number">0x07</span>,</span> <span class="line" id="L24"> same_value = <span class="tok-number">0x08</span>,</span> <span class="line" id="L25"> register = <span class="tok-number">0x09</span>,</span> <span class="line" id="L26"> remember_state = <span class="tok-number">0x0a</span>,</span> <span class="line" id="L27"> restore_state = <span class="tok-number">0x0b</span>,</span> <span class="line" id="L28"> def_cfa = <span class="tok-number">0x0c</span>,</span> <span class="line" id="L29"> def_cfa_register = <span class="tok-number">0x0d</span>,</span> <span class="line" id="L30"> def_cfa_offset = <span class="tok-number">0x0e</span>,</span> <span class="line" id="L31"> def_cfa_expression = <span class="tok-number">0x0f</span>,</span> <span class="line" id="L32"> expression = <span class="tok-number">0x10</span>,</span> <span class="line" id="L33"> offset_extended_sf = <span class="tok-number">0x11</span>,</span> <span class="line" id="L34"> def_cfa_sf = <span class="tok-number">0x12</span>,</span> <span class="line" id="L35"> def_cfa_offset_sf = <span class="tok-number">0x13</span>,</span> <span class="line" id="L36"> val_offset = <span class="tok-number">0x14</span>,</span> <span class="line" id="L37"> val_offset_sf = <span class="tok-number">0x15</span>,</span> <span class="line" id="L38"> val_expression = <span class="tok-number">0x16</span>,</span> <span class="line" id="L39"></span> <span class="line" id="L40"> <span class="tok-comment">// These opcodes encode an operand in the lower 6 bits of the opcode itself</span> </span> <span class="line" id="L41"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_inline = <span class="tok-builtin">@intFromEnum</span>(Opcode.advance_loc);</span> <span class="line" id="L42"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_inline = <span class="tok-builtin">@intFromEnum</span>(Opcode.restore) | <span class="tok-number">0b111111</span>;</span> <span class="line" id="L43"></span> <span class="line" id="L44"> <span class="tok-comment">// These opcodes are trailed by zero or more operands</span> </span> <span class="line" id="L45"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_reserved = <span class="tok-builtin">@intFromEnum</span>(Opcode.nop);</span> <span class="line" id="L46"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_reserved = <span class="tok-builtin">@intFromEnum</span>(Opcode.val_expression);</span> <span class="line" id="L47"></span> <span class="line" id="L48"> <span class="tok-comment">// Vendor-specific opcodes</span> </span> <span class="line" id="L49"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_user = <span class="tok-number">0x1c</span>;</span> <span class="line" id="L50"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_user = <span class="tok-number">0x3f</span>;</span> <span class="line" id="L51">};</span> <span class="line" id="L52"></span> <span class="line" id="L53"><span class="tok-kw">const</span> Operand = <span class="tok-kw">enum</span> {</span> <span class="line" id="L54"> opcode_delta,</span> <span class="line" id="L55"> opcode_register,</span> <span class="line" id="L56"> uleb128_register,</span> <span class="line" id="L57"> uleb128_offset,</span> <span class="line" id="L58"> sleb128_offset,</span> <span class="line" id="L59"> address,</span> <span class="line" id="L60"> u8_delta,</span> <span class="line" id="L61"> u16_delta,</span> <span class="line" id="L62"> u32_delta,</span> <span class="line" id="L63"> block,</span> <span class="line" id="L64"></span> <span class="line" id="L65"> <span class="tok-kw">fn</span> <span class="tok-fn">Storage</span>(<span class="tok-kw">comptime</span> self: Operand) <span class="tok-type">type</span> {</span> <span class="line" id="L66"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (self) {</span> <span class="line" id="L67"> .opcode_delta, .opcode_register =&gt; <span class="tok-type">u8</span>,</span> <span class="line" id="L68"> .uleb128_register =&gt; <span class="tok-type">u8</span>,</span> <span class="line" id="L69"> .uleb128_offset =&gt; <span class="tok-type">u64</span>,</span> <span class="line" id="L70"> .sleb128_offset =&gt; <span class="tok-type">i64</span>,</span> <span class="line" id="L71"> .address =&gt; <span class="tok-type">u64</span>,</span> <span class="line" id="L72"> .u8_delta =&gt; <span class="tok-type">u8</span>,</span> <span class="line" id="L73"> .u16_delta =&gt; <span class="tok-type">u16</span>,</span> <span class="line" id="L74"> .u32_delta =&gt; <span class="tok-type">u32</span>,</span> <span class="line" id="L75"> .block =&gt; []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L76"> };</span> <span class="line" id="L77"> }</span> <span class="line" id="L78"></span> <span class="line" id="L79"> <span class="tok-kw">fn</span> <span class="tok-fn">read</span>(</span> <span class="line" id="L80"> <span class="tok-kw">comptime</span> self: Operand,</span> <span class="line" id="L81"> stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>),</span> <span class="line" id="L82"> opcode_value: ?<span class="tok-type">u6</span>,</span> <span class="line" id="L83"> addr_size_bytes: <span class="tok-type">u8</span>,</span> <span class="line" id="L84"> endian: std.builtin.Endian,</span> <span class="line" id="L85"> ) !Storage(self) {</span> <span class="line" id="L86"> <span class="tok-kw">const</span> reader = stream.reader();</span> <span class="line" id="L87"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (self) {</span> <span class="line" id="L88"> .opcode_delta, .opcode_register =&gt; opcode_value <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperand,</span> <span class="line" id="L89"> .uleb128_register =&gt; <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader),</span> <span class="line" id="L90"> .uleb128_offset =&gt; <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u64</span>, reader),</span> <span class="line" id="L91"> .sleb128_offset =&gt; <span class="tok-kw">try</span> leb.readILEB128(<span class="tok-type">i64</span>, reader),</span> <span class="line" id="L92"> .address =&gt; <span class="tok-kw">switch</span> (addr_size_bytes) {</span> <span class="line" id="L93"> <span class="tok-number">2</span> =&gt; <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u16</span>, endian),</span> <span class="line" id="L94"> <span class="tok-number">4</span> =&gt; <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u32</span>, endian),</span> <span class="line" id="L95"> <span class="tok-number">8</span> =&gt; <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u64</span>, endian),</span> <span class="line" id="L96"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidAddrSize,</span> <span class="line" id="L97"> },</span> <span class="line" id="L98"> .u8_delta =&gt; <span class="tok-kw">try</span> reader.readByte(),</span> <span class="line" id="L99"> .u16_delta =&gt; <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u16</span>, endian),</span> <span class="line" id="L100"> .u32_delta =&gt; <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u32</span>, endian),</span> <span class="line" id="L101"> .block =&gt; {</span> <span class="line" id="L102"> <span class="tok-kw">const</span> block_len = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">usize</span>, reader);</span> <span class="line" id="L103"> <span class="tok-kw">if</span> (stream.pos + block_len &gt; stream.buffer.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperand;</span> <span class="line" id="L104"></span> <span class="line" id="L105"> <span class="tok-kw">const</span> block = stream.buffer[stream.pos..][<span class="tok-number">0</span>..block_len];</span> <span class="line" id="L106"> reader.context.pos += block_len;</span> <span class="line" id="L107"></span> <span class="line" id="L108"> <span class="tok-kw">return</span> block;</span> <span class="line" id="L109"> },</span> <span class="line" id="L110"> };</span> <span class="line" id="L111"> }</span> <span class="line" id="L112">};</span> <span class="line" id="L113"></span> <span class="line" id="L114"><span class="tok-kw">fn</span> <span class="tok-fn">InstructionType</span>(<span class="tok-kw">comptime</span> definition: <span class="tok-kw">anytype</span>) <span class="tok-type">type</span> {</span> <span class="line" id="L115"> <span class="tok-kw">const</span> definition_type = <span class="tok-builtin">@typeInfo</span>(<span class="tok-builtin">@TypeOf</span>(definition));</span> <span class="line" id="L116"> assert(definition_type == .Struct);</span> <span class="line" id="L117"></span> <span class="line" id="L118"> <span class="tok-kw">const</span> definition_len = definition_type.Struct.fields.len;</span> <span class="line" id="L119"> <span class="tok-kw">comptime</span> <span class="tok-kw">var</span> fields: [definition_len]std.builtin.Type.StructField = <span class="tok-null">undefined</span>;</span> <span class="line" id="L120"> <span class="tok-kw">inline</span> <span class="tok-kw">for</span> (definition_type.Struct.fields, &amp;fields) |definition_field, *operands_field| {</span> <span class="line" id="L121"> <span class="tok-kw">const</span> opcode = std.enums.nameCast(Operand, <span class="tok-builtin">@field</span>(definition, definition_field.name));</span> <span class="line" id="L122"> <span class="tok-kw">const</span> storage_type = opcode.Storage();</span> <span class="line" id="L123"> operands_field.* = .{</span> <span class="line" id="L124"> .name = definition_field.name,</span> <span class="line" id="L125"> .<span class="tok-type">type</span> = storage_type,</span> <span class="line" id="L126"> .default_value = <span class="tok-null">null</span>,</span> <span class="line" id="L127"> .is_comptime = <span class="tok-null">false</span>,</span> <span class="line" id="L128"> .alignment = <span class="tok-builtin">@alignOf</span>(storage_type),</span> <span class="line" id="L129"> };</span> <span class="line" id="L130"> }</span> <span class="line" id="L131"></span> <span class="line" id="L132"> <span class="tok-kw">const</span> InstructionOperands = <span class="tok-builtin">@Type</span>(.{</span> <span class="line" id="L133"> .Struct = .{</span> <span class="line" id="L134"> .layout = .Auto,</span> <span class="line" id="L135"> .fields = &amp;fields,</span> <span class="line" id="L136"> .decls = &amp;.{},</span> <span class="line" id="L137"> .is_tuple = <span class="tok-null">false</span>,</span> <span class="line" id="L138"> },</span> <span class="line" id="L139"> });</span> <span class="line" id="L140"></span> <span class="line" id="L141"> <span class="tok-kw">return</span> <span class="tok-kw">struct</span> {</span> <span class="line" id="L142"> <span class="tok-kw">const</span> Self = <span class="tok-builtin">@This</span>();</span> <span class="line" id="L143"> operands: InstructionOperands,</span> <span class="line" id="L144"></span> <span class="line" id="L145"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">read</span>(</span> <span class="line" id="L146"> stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>),</span> <span class="line" id="L147"> opcode_value: ?<span class="tok-type">u6</span>,</span> <span class="line" id="L148"> addr_size_bytes: <span class="tok-type">u8</span>,</span> <span class="line" id="L149"> endian: std.builtin.Endian,</span> <span class="line" id="L150"> ) !Self {</span> <span class="line" id="L151"> <span class="tok-kw">var</span> operands: InstructionOperands = <span class="tok-null">undefined</span>;</span> <span class="line" id="L152"> <span class="tok-kw">inline</span> <span class="tok-kw">for</span> (definition_type.Struct.fields) |definition_field| {</span> <span class="line" id="L153"> <span class="tok-kw">const</span> operand = <span class="tok-kw">comptime</span> std.enums.nameCast(Operand, <span class="tok-builtin">@field</span>(definition, definition_field.name));</span> <span class="line" id="L154"> <span class="tok-builtin">@field</span>(operands, definition_field.name) = <span class="tok-kw">try</span> operand.read(stream, opcode_value, addr_size_bytes, endian);</span> <span class="line" id="L155"> }</span> <span class="line" id="L156"></span> <span class="line" id="L157"> <span class="tok-kw">return</span> .{ .operands = operands };</span> <span class="line" id="L158"> }</span> <span class="line" id="L159"> };</span> <span class="line" id="L160">}</span> <span class="line" id="L161"></span> <span class="line" id="L162"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Instruction = <span class="tok-kw">union</span>(Opcode) {</span> <span class="line" id="L163"> advance_loc: InstructionType(.{ .delta = .opcode_delta }),</span> <span class="line" id="L164"> offset: InstructionType(.{ .register = .opcode_register, .offset = .uleb128_offset }),</span> <span class="line" id="L165"> offset_extended: InstructionType(.{ .register = .uleb128_register, .offset = .uleb128_offset }),</span> <span class="line" id="L166"> restore: InstructionType(.{ .register = .opcode_register }),</span> <span class="line" id="L167"> restore_extended: InstructionType(.{ .register = .uleb128_register }),</span> <span class="line" id="L168"> nop: InstructionType(.{}),</span> <span class="line" id="L169"> set_loc: InstructionType(.{ .address = .address }),</span> <span class="line" id="L170"> advance_loc1: InstructionType(.{ .delta = .u8_delta }),</span> <span class="line" id="L171"> advance_loc2: InstructionType(.{ .delta = .u16_delta }),</span> <span class="line" id="L172"> advance_loc4: InstructionType(.{ .delta = .u32_delta }),</span> <span class="line" id="L173"> <span class="tok-null">undefined</span>: InstructionType(.{ .register = .uleb128_register }),</span> <span class="line" id="L174"> same_value: InstructionType(.{ .register = .uleb128_register }),</span> <span class="line" id="L175"> register: InstructionType(.{ .register = .uleb128_register, .target_register = .uleb128_register }),</span> <span class="line" id="L176"> remember_state: InstructionType(.{}),</span> <span class="line" id="L177"> restore_state: InstructionType(.{}),</span> <span class="line" id="L178"> def_cfa: InstructionType(.{ .register = .uleb128_register, .offset = .uleb128_offset }),</span> <span class="line" id="L179"> def_cfa_register: InstructionType(.{ .register = .uleb128_register }),</span> <span class="line" id="L180"> def_cfa_offset: InstructionType(.{ .offset = .uleb128_offset }),</span> <span class="line" id="L181"> def_cfa_expression: InstructionType(.{ .block = .block }),</span> <span class="line" id="L182"> expression: InstructionType(.{ .register = .uleb128_register, .block = .block }),</span> <span class="line" id="L183"> offset_extended_sf: InstructionType(.{ .register = .uleb128_register, .offset = .sleb128_offset }),</span> <span class="line" id="L184"> def_cfa_sf: InstructionType(.{ .register = .uleb128_register, .offset = .sleb128_offset }),</span> <span class="line" id="L185"> def_cfa_offset_sf: InstructionType(.{ .offset = .sleb128_offset }),</span> <span class="line" id="L186"> val_offset: InstructionType(.{ .register = .uleb128_register, .offset = .uleb128_offset }),</span> <span class="line" id="L187"> val_offset_sf: InstructionType(.{ .register = .uleb128_register, .offset = .sleb128_offset }),</span> <span class="line" id="L188"> val_expression: InstructionType(.{ .register = .uleb128_register, .block = .block }),</span> <span class="line" id="L189"></span> <span class="line" id="L190"> <span class="tok-kw">fn</span> <span class="tok-fn">readOperands</span>(</span> <span class="line" id="L191"> self: *Instruction,</span> <span class="line" id="L192"> stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>),</span> <span class="line" id="L193"> opcode_value: ?<span class="tok-type">u6</span>,</span> <span class="line" id="L194"> addr_size_bytes: <span class="tok-type">u8</span>,</span> <span class="line" id="L195"> endian: std.builtin.Endian,</span> <span class="line" id="L196"> ) !<span class="tok-type">void</span> {</span> <span class="line" id="L197"> <span class="tok-kw">switch</span> (self.*) {</span> <span class="line" id="L198"> <span class="tok-kw">inline</span> <span class="tok-kw">else</span> =&gt; |*inst| inst.* = <span class="tok-kw">try</span> <span class="tok-builtin">@TypeOf</span>(inst.*).read(stream, opcode_value, addr_size_bytes, endian),</span> <span class="line" id="L199"> }</span> <span class="line" id="L200"> }</span> <span class="line" id="L201"></span> <span class="line" id="L202"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">read</span>(</span> <span class="line" id="L203"> stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>),</span> <span class="line" id="L204"> addr_size_bytes: <span class="tok-type">u8</span>,</span> <span class="line" id="L205"> endian: std.builtin.Endian,</span> <span class="line" id="L206"> ) !Instruction {</span> <span class="line" id="L207"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (<span class="tok-kw">try</span> stream.reader().readByte()) {</span> <span class="line" id="L208"> <span class="tok-kw">inline</span> Opcode.lo_inline...Opcode.hi_inline =&gt; |opcode| blk: {</span> <span class="line" id="L209"> <span class="tok-kw">const</span> e: Opcode = <span class="tok-builtin">@enumFromInt</span>(opcode &amp; <span class="tok-number">0b11000000</span>);</span> <span class="line" id="L210"> <span class="tok-kw">var</span> result = <span class="tok-builtin">@unionInit</span>(Instruction, <span class="tok-builtin">@tagName</span>(e), <span class="tok-null">undefined</span>);</span> <span class="line" id="L211"> <span class="tok-kw">try</span> result.readOperands(stream, <span class="tok-builtin">@as</span>(<span class="tok-type">u6</span>, <span class="tok-builtin">@intCast</span>(opcode &amp; <span class="tok-number">0b111111</span>)), addr_size_bytes, endian);</span> <span class="line" id="L212"> <span class="tok-kw">break</span> :blk result;</span> <span class="line" id="L213"> },</span> <span class="line" id="L214"> <span class="tok-kw">inline</span> Opcode.lo_reserved...Opcode.hi_reserved =&gt; |opcode| blk: {</span> <span class="line" id="L215"> <span class="tok-kw">const</span> e: Opcode = <span class="tok-builtin">@enumFromInt</span>(opcode);</span> <span class="line" id="L216"> <span class="tok-kw">var</span> result = <span class="tok-builtin">@unionInit</span>(Instruction, <span class="tok-builtin">@tagName</span>(e), <span class="tok-null">undefined</span>);</span> <span class="line" id="L217"> <span class="tok-kw">try</span> result.readOperands(stream, <span class="tok-null">null</span>, addr_size_bytes, endian);</span> <span class="line" id="L218"> <span class="tok-kw">break</span> :blk result;</span> <span class="line" id="L219"> },</span> <span class="line" id="L220"> Opcode.lo_user...Opcode.hi_user =&gt; <span class="tok-kw">error</span>.UnimplementedUserOpcode,</span> <span class="line" id="L221"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">error</span>.InvalidOpcode,</span> <span class="line" id="L222"> };</span> <span class="line" id="L223"> }</span> <span class="line" id="L224">};</span> <span class="line" id="L225"></span> <span class="line" id="L226"><span class="tok-comment">/// Since register rules are applied (usually) during a panic,</span></span> <span class="line" id="L227"><span class="tok-comment">/// checked addition / subtraction is used so that we can return</span></span> <span class="line" id="L228"><span class="tok-comment">/// an error and fall back to FP-based unwinding.</span></span> <span class="line" id="L229"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">applyOffset</span>(base: <span class="tok-type">usize</span>, offset: <span class="tok-type">i64</span>) !<span class="tok-type">usize</span> {</span> <span class="line" id="L230"> <span class="tok-kw">return</span> <span class="tok-kw">if</span> (offset &gt;= <span class="tok-number">0</span>)</span> <span class="line" id="L231"> <span class="tok-kw">try</span> std.math.add(<span class="tok-type">usize</span>, base, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@intCast</span>(offset)))</span> <span class="line" id="L232"> <span class="tok-kw">else</span></span> <span class="line" id="L233"> <span class="tok-kw">try</span> std.math.sub(<span class="tok-type">usize</span>, base, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@intCast</span>(-offset)));</span> <span class="line" id="L234">}</span> <span class="line" id="L235"></span> <span class="line" id="L236"><span class="tok-comment">/// This is a virtual machine that runs DWARF call frame instructions.</span></span> <span class="line" id="L237"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> VirtualMachine = <span class="tok-kw">struct</span> {</span> <span class="line" id="L238"> <span class="tok-comment">/// See section 6.4.1 of the DWARF5 specification for details on each</span></span> <span class="line" id="L239"> <span class="tok-kw">const</span> RegisterRule = <span class="tok-kw">union</span>(<span class="tok-kw">enum</span>) {</span> <span class="line" id="L240"> <span class="tok-comment">// The spec says that the default rule for each column is the undefined rule.</span> </span> <span class="line" id="L241"> <span class="tok-comment">// However, it also allows ABI / compiler authors to specify alternate defaults, so</span> </span> <span class="line" id="L242"> <span class="tok-comment">// there is a distinction made here.</span> </span> <span class="line" id="L243"> default: <span class="tok-type">void</span>,</span> <span class="line" id="L244"></span> <span class="line" id="L245"> <span class="tok-null">undefined</span>: <span class="tok-type">void</span>,</span> <span class="line" id="L246"> same_value: <span class="tok-type">void</span>,</span> <span class="line" id="L247"></span> <span class="line" id="L248"> <span class="tok-comment">// offset(N)</span> </span> <span class="line" id="L249"> offset: <span class="tok-type">i64</span>,</span> <span class="line" id="L250"></span> <span class="line" id="L251"> <span class="tok-comment">// val_offset(N)</span> </span> <span class="line" id="L252"> val_offset: <span class="tok-type">i64</span>,</span> <span class="line" id="L253"></span> <span class="line" id="L254"> <span class="tok-comment">// register(R)</span> </span> <span class="line" id="L255"> register: <span class="tok-type">u8</span>,</span> <span class="line" id="L256"></span> <span class="line" id="L257"> <span class="tok-comment">// expression(E)</span> </span> <span class="line" id="L258"> expression: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L259"></span> <span class="line" id="L260"> <span class="tok-comment">// val_expression(E)</span> </span> <span class="line" id="L261"> val_expression: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L262"></span> <span class="line" id="L263"> <span class="tok-comment">// Augmenter-defined rule</span> </span> <span class="line" id="L264"> architectural: <span class="tok-type">void</span>,</span> <span class="line" id="L265"> };</span> <span class="line" id="L266"></span> <span class="line" id="L267"> <span class="tok-comment">/// Each row contains unwinding rules for a set of registers.</span></span> <span class="line" id="L268"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> Row = <span class="tok-kw">struct</span> {</span> <span class="line" id="L269"> <span class="tok-comment">/// Offset from `FrameDescriptionEntry.pc_begin`</span></span> <span class="line" id="L270"> offset: <span class="tok-type">u64</span> = <span class="tok-number">0</span>,</span> <span class="line" id="L271"></span> <span class="line" id="L272"> <span class="tok-comment">/// Special-case column that defines the CFA (Canonical Frame Address) rule.</span></span> <span class="line" id="L273"> <span class="tok-comment">/// The register field of this column defines the register that CFA is derived from.</span></span> <span class="line" id="L274"> cfa: Column = .{},</span> <span class="line" id="L275"></span> <span class="line" id="L276"> <span class="tok-comment">/// The register fields in these columns define the register the rule applies to.</span></span> <span class="line" id="L277"> columns: ColumnRange = .{},</span> <span class="line" id="L278"></span> <span class="line" id="L279"> <span class="tok-comment">/// Indicates that the next write to any column in this row needs to copy</span></span> <span class="line" id="L280"> <span class="tok-comment">/// the backing column storage first, as it may be referenced by previous rows.</span></span> <span class="line" id="L281"> copy_on_write: <span class="tok-type">bool</span> = <span class="tok-null">false</span>,</span> <span class="line" id="L282"> };</span> <span class="line" id="L283"></span> <span class="line" id="L284"> <span class="tok-kw">pub</span> <span class="tok-kw">const</span> Column = <span class="tok-kw">struct</span> {</span> <span class="line" id="L285"> register: ?<span class="tok-type">u8</span> = <span class="tok-null">null</span>,</span> <span class="line" id="L286"> rule: RegisterRule = .{ .default = {} },</span> <span class="line" id="L287"></span> <span class="line" id="L288"> <span class="tok-comment">/// Resolves the register rule and places the result into `out` (see dwarf.abi.regBytes)</span></span> <span class="line" id="L289"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">resolveValue</span>(</span> <span class="line" id="L290"> self: Column,</span> <span class="line" id="L291"> context: *dwarf.UnwindContext,</span> <span class="line" id="L292"> expression_context: dwarf.expressions.ExpressionContext,</span> <span class="line" id="L293"> out: []<span class="tok-type">u8</span>,</span> <span class="line" id="L294"> ) !<span class="tok-type">void</span> {</span> <span class="line" id="L295"> <span class="tok-kw">switch</span> (self.rule) {</span> <span class="line" id="L296"> .default =&gt; {</span> <span class="line" id="L297"> <span class="tok-kw">const</span> register = self.register <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidRegister;</span> <span class="line" id="L298"> <span class="tok-kw">try</span> abi.getRegDefaultValue(register, context, out);</span> <span class="line" id="L299"> },</span> <span class="line" id="L300"> .<span class="tok-null">undefined</span> =&gt; {</span> <span class="line" id="L301"> <span class="tok-builtin">@memset</span>(out, <span class="tok-null">undefined</span>);</span> <span class="line" id="L302"> },</span> <span class="line" id="L303"> .same_value =&gt; {</span> <span class="line" id="L304"> <span class="tok-comment">// TODO: This copy could be eliminated if callers always copy the state then call this function to update it</span> </span> <span class="line" id="L305"> <span class="tok-kw">const</span> register = self.register <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidRegister;</span> <span class="line" id="L306"> <span class="tok-kw">const</span> src = <span class="tok-kw">try</span> abi.regBytes(context.thread_context, register, context.reg_context);</span> <span class="line" id="L307"> <span class="tok-kw">if</span> (src.len != out.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.RegisterSizeMismatch;</span> <span class="line" id="L308"> <span class="tok-builtin">@memcpy</span>(out, src);</span> <span class="line" id="L309"> },</span> <span class="line" id="L310"> .offset =&gt; |offset| {</span> <span class="line" id="L311"> <span class="tok-kw">if</span> (context.cfa) |cfa| {</span> <span class="line" id="L312"> <span class="tok-kw">const</span> addr = <span class="tok-kw">try</span> applyOffset(cfa, offset);</span> <span class="line" id="L313"> <span class="tok-kw">if</span> (expression_context.isValidMemory) |isValidMemory| <span class="tok-kw">if</span> (!isValidMemory(addr)) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidAddress;</span> <span class="line" id="L314"> <span class="tok-kw">const</span> ptr: *<span class="tok-kw">const</span> <span class="tok-type">usize</span> = <span class="tok-builtin">@ptrFromInt</span>(addr);</span> <span class="line" id="L315"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, out, ptr.*);</span> <span class="line" id="L316"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFA;</span> <span class="line" id="L317"> },</span> <span class="line" id="L318"> .val_offset =&gt; |offset| {</span> <span class="line" id="L319"> <span class="tok-kw">if</span> (context.cfa) |cfa| {</span> <span class="line" id="L320"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, out, <span class="tok-kw">try</span> applyOffset(cfa, offset));</span> <span class="line" id="L321"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFA;</span> <span class="line" id="L322"> },</span> <span class="line" id="L323"> .register =&gt; |register| {</span> <span class="line" id="L324"> <span class="tok-kw">const</span> src = <span class="tok-kw">try</span> abi.regBytes(context.thread_context, register, context.reg_context);</span> <span class="line" id="L325"> <span class="tok-kw">if</span> (src.len != out.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.RegisterSizeMismatch;</span> <span class="line" id="L326"> <span class="tok-builtin">@memcpy</span>(out, <span class="tok-kw">try</span> abi.regBytes(context.thread_context, register, context.reg_context));</span> <span class="line" id="L327"> },</span> <span class="line" id="L328"> .expression =&gt; |expression| {</span> <span class="line" id="L329"> context.stack_machine.reset();</span> <span class="line" id="L330"> <span class="tok-kw">const</span> value = <span class="tok-kw">try</span> context.stack_machine.run(expression, context.allocator, expression_context, context.cfa.?);</span> <span class="line" id="L331"> <span class="tok-kw">const</span> addr = <span class="tok-kw">if</span> (value) |v| blk: {</span> <span class="line" id="L332"> <span class="tok-kw">if</span> (v != .generic) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpressionValue;</span> <span class="line" id="L333"> <span class="tok-kw">break</span> :blk v.generic;</span> <span class="line" id="L334"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.NoExpressionValue;</span> <span class="line" id="L335"></span> <span class="line" id="L336"> <span class="tok-kw">if</span> (!context.isValidMemory(addr)) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpressionAddress;</span> <span class="line" id="L337"> <span class="tok-kw">const</span> ptr: *<span class="tok-type">usize</span> = <span class="tok-builtin">@ptrFromInt</span>(addr);</span> <span class="line" id="L338"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, out, ptr.*);</span> <span class="line" id="L339"> },</span> <span class="line" id="L340"> .val_expression =&gt; |expression| {</span> <span class="line" id="L341"> context.stack_machine.reset();</span> <span class="line" id="L342"> <span class="tok-kw">const</span> value = <span class="tok-kw">try</span> context.stack_machine.run(expression, context.allocator, expression_context, context.cfa.?);</span> <span class="line" id="L343"> <span class="tok-kw">if</span> (value) |v| {</span> <span class="line" id="L344"> <span class="tok-kw">if</span> (v != .generic) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpressionValue;</span> <span class="line" id="L345"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, out, v.generic);</span> <span class="line" id="L346"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.NoExpressionValue;</span> <span class="line" id="L347"> },</span> <span class="line" id="L348"> .architectural =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedRegisterRule,</span> <span class="line" id="L349"> }</span> <span class="line" id="L350"> }</span> <span class="line" id="L351"> };</span> <span class="line" id="L352"></span> <span class="line" id="L353"> <span class="tok-kw">const</span> ColumnRange = <span class="tok-kw">struct</span> {</span> <span class="line" id="L354"> <span class="tok-comment">/// Index into `columns` of the first column in this row.</span></span> <span class="line" id="L355"> start: <span class="tok-type">usize</span> = <span class="tok-null">undefined</span>,</span> <span class="line" id="L356"> len: <span class="tok-type">u8</span> = <span class="tok-number">0</span>,</span> <span class="line" id="L357"> };</span> <span class="line" id="L358"></span> <span class="line" id="L359"> columns: std.ArrayListUnmanaged(Column) = .{},</span> <span class="line" id="L360"> stack: std.ArrayListUnmanaged(ColumnRange) = .{},</span> <span class="line" id="L361"> current_row: Row = .{},</span> <span class="line" id="L362"></span> <span class="line" id="L363"> <span class="tok-comment">/// The result of executing the CIE's initial_instructions</span></span> <span class="line" id="L364"> cie_row: ?Row = <span class="tok-null">null</span>,</span> <span class="line" id="L365"></span> <span class="line" id="L366"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">deinit</span>(self: *VirtualMachine, allocator: std.mem.Allocator) <span class="tok-type">void</span> {</span> <span class="line" id="L367"> self.stack.deinit(allocator);</span> <span class="line" id="L368"> self.columns.deinit(allocator);</span> <span class="line" id="L369"> self.* = <span class="tok-null">undefined</span>;</span> <span class="line" id="L370"> }</span> <span class="line" id="L371"></span> <span class="line" id="L372"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">reset</span>(self: *VirtualMachine) <span class="tok-type">void</span> {</span> <span class="line" id="L373"> self.stack.clearRetainingCapacity();</span> <span class="line" id="L374"> self.columns.clearRetainingCapacity();</span> <span class="line" id="L375"> self.current_row = .{};</span> <span class="line" id="L376"> self.cie_row = <span class="tok-null">null</span>;</span> <span class="line" id="L377"> }</span> <span class="line" id="L378"></span> <span class="line" id="L379"> <span class="tok-comment">/// Return a slice backed by the row's non-CFA columns</span></span> <span class="line" id="L380"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">rowColumns</span>(self: VirtualMachine, row: Row) []Column {</span> <span class="line" id="L381"> <span class="tok-kw">return</span> self.columns.items[row.columns.start..][<span class="tok-number">0</span>..row.columns.len];</span> <span class="line" id="L382"> }</span> <span class="line" id="L383"></span> <span class="line" id="L384"> <span class="tok-comment">/// Either retrieves or adds a column for `register` (non-CFA) in the current row.</span></span> <span class="line" id="L385"> <span class="tok-kw">fn</span> <span class="tok-fn">getOrAddColumn</span>(self: *VirtualMachine, allocator: std.mem.Allocator, register: <span class="tok-type">u8</span>) !*Column {</span> <span class="line" id="L386"> <span class="tok-kw">for</span> (self.rowColumns(self.current_row)) |*c| {</span> <span class="line" id="L387"> <span class="tok-kw">if</span> (c.register == register) <span class="tok-kw">return</span> c;</span> <span class="line" id="L388"> }</span> <span class="line" id="L389"></span> <span class="line" id="L390"> <span class="tok-kw">if</span> (self.current_row.columns.len == <span class="tok-number">0</span>) {</span> <span class="line" id="L391"> self.current_row.columns.start = self.columns.items.len;</span> <span class="line" id="L392"> }</span> <span class="line" id="L393"> self.current_row.columns.len += <span class="tok-number">1</span>;</span> <span class="line" id="L394"></span> <span class="line" id="L395"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.columns.addOne(allocator);</span> <span class="line" id="L396"> column.* = .{</span> <span class="line" id="L397"> .register = register,</span> <span class="line" id="L398"> };</span> <span class="line" id="L399"></span> <span class="line" id="L400"> <span class="tok-kw">return</span> column;</span> <span class="line" id="L401"> }</span> <span class="line" id="L402"></span> <span class="line" id="L403"> <span class="tok-comment">/// Runs the CIE instructions, then the FDE instructions. Execution halts</span></span> <span class="line" id="L404"> <span class="tok-comment">/// once the row that corresponds to `pc` is known, and the row is returned.</span></span> <span class="line" id="L405"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">runTo</span>(</span> <span class="line" id="L406"> self: *VirtualMachine,</span> <span class="line" id="L407"> allocator: std.mem.Allocator,</span> <span class="line" id="L408"> pc: <span class="tok-type">u64</span>,</span> <span class="line" id="L409"> cie: dwarf.CommonInformationEntry,</span> <span class="line" id="L410"> fde: dwarf.FrameDescriptionEntry,</span> <span class="line" id="L411"> addr_size_bytes: <span class="tok-type">u8</span>,</span> <span class="line" id="L412"> endian: std.builtin.Endian,</span> <span class="line" id="L413"> ) !Row {</span> <span class="line" id="L414"> assert(self.cie_row == <span class="tok-null">null</span>);</span> <span class="line" id="L415"> <span class="tok-kw">if</span> (pc &lt; fde.pc_begin <span class="tok-kw">or</span> pc &gt;= fde.pc_begin + fde.pc_range) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.AddressOutOfRange;</span> <span class="line" id="L416"></span> <span class="line" id="L417"> <span class="tok-kw">var</span> prev_row: Row = self.current_row;</span> <span class="line" id="L418"></span> <span class="line" id="L419"> <span class="tok-kw">var</span> cie_stream = std.io.fixedBufferStream(cie.initial_instructions);</span> <span class="line" id="L420"> <span class="tok-kw">var</span> fde_stream = std.io.fixedBufferStream(fde.instructions);</span> <span class="line" id="L421"> <span class="tok-kw">var</span> streams = [_]*std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>){</span> <span class="line" id="L422"> &amp;cie_stream,</span> <span class="line" id="L423"> &amp;fde_stream,</span> <span class="line" id="L424"> };</span> <span class="line" id="L425"></span> <span class="line" id="L426"> <span class="tok-kw">for</span> (&amp;streams, <span class="tok-number">0</span>..) |stream, i| {</span> <span class="line" id="L427"> <span class="tok-kw">while</span> (stream.pos &lt; stream.buffer.len) {</span> <span class="line" id="L428"> <span class="tok-kw">const</span> instruction = <span class="tok-kw">try</span> dwarf.call_frame.Instruction.read(stream, addr_size_bytes, endian);</span> <span class="line" id="L429"> prev_row = <span class="tok-kw">try</span> self.step(allocator, cie, i == <span class="tok-number">0</span>, instruction);</span> <span class="line" id="L430"> <span class="tok-kw">if</span> (pc &lt; fde.pc_begin + self.current_row.offset) <span class="tok-kw">return</span> prev_row;</span> <span class="line" id="L431"> }</span> <span class="line" id="L432"> }</span> <span class="line" id="L433"></span> <span class="line" id="L434"> <span class="tok-kw">return</span> self.current_row;</span> <span class="line" id="L435"> }</span> <span class="line" id="L436"></span> <span class="line" id="L437"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">runToNative</span>(</span> <span class="line" id="L438"> self: *VirtualMachine,</span> <span class="line" id="L439"> allocator: std.mem.Allocator,</span> <span class="line" id="L440"> pc: <span class="tok-type">u64</span>,</span> <span class="line" id="L441"> cie: dwarf.CommonInformationEntry,</span> <span class="line" id="L442"> fde: dwarf.FrameDescriptionEntry,</span> <span class="line" id="L443"> ) !Row {</span> <span class="line" id="L444"> <span class="tok-kw">return</span> self.runTo(allocator, pc, cie, fde, <span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>), builtin.target.cpu.arch.endian());</span> <span class="line" id="L445"> }</span> <span class="line" id="L446"></span> <span class="line" id="L447"> <span class="tok-kw">fn</span> <span class="tok-fn">resolveCopyOnWrite</span>(self: *VirtualMachine, allocator: std.mem.Allocator) !<span class="tok-type">void</span> {</span> <span class="line" id="L448"> <span class="tok-kw">if</span> (!self.current_row.copy_on_write) <span class="tok-kw">return</span>;</span> <span class="line" id="L449"></span> <span class="line" id="L450"> <span class="tok-kw">const</span> new_start = self.columns.items.len;</span> <span class="line" id="L451"> <span class="tok-kw">if</span> (self.current_row.columns.len &gt; <span class="tok-number">0</span>) {</span> <span class="line" id="L452"> <span class="tok-kw">try</span> self.columns.ensureUnusedCapacity(allocator, self.current_row.columns.len);</span> <span class="line" id="L453"> self.columns.appendSliceAssumeCapacity(self.rowColumns(self.current_row));</span> <span class="line" id="L454"> self.current_row.columns.start = new_start;</span> <span class="line" id="L455"> }</span> <span class="line" id="L456"> }</span> <span class="line" id="L457"></span> <span class="line" id="L458"> <span class="tok-comment">/// Executes a single instruction.</span></span> <span class="line" id="L459"> <span class="tok-comment">/// If this instruction is from the CIE, `is_initial` should be set.</span></span> <span class="line" id="L460"> <span class="tok-comment">/// Returns the value of `current_row` before executing this instruction.</span></span> <span class="line" id="L461"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">step</span>(</span> <span class="line" id="L462"> self: *VirtualMachine,</span> <span class="line" id="L463"> allocator: std.mem.Allocator,</span> <span class="line" id="L464"> cie: dwarf.CommonInformationEntry,</span> <span class="line" id="L465"> is_initial: <span class="tok-type">bool</span>,</span> <span class="line" id="L466"> instruction: Instruction,</span> <span class="line" id="L467"> ) !Row {</span> <span class="line" id="L468"> <span class="tok-comment">// CIE instructions must be run before FDE instructions</span> </span> <span class="line" id="L469"> assert(!is_initial <span class="tok-kw">or</span> self.cie_row == <span class="tok-null">null</span>);</span> <span class="line" id="L470"> <span class="tok-kw">if</span> (!is_initial <span class="tok-kw">and</span> self.cie_row == <span class="tok-null">null</span>) {</span> <span class="line" id="L471"> self.cie_row = self.current_row;</span> <span class="line" id="L472"> self.current_row.copy_on_write = <span class="tok-null">true</span>;</span> <span class="line" id="L473"> }</span> <span class="line" id="L474"></span> <span class="line" id="L475"> <span class="tok-kw">const</span> prev_row = self.current_row;</span> <span class="line" id="L476"> <span class="tok-kw">switch</span> (instruction) {</span> <span class="line" id="L477"> .set_loc =&gt; |i| {</span> <span class="line" id="L478"> <span class="tok-kw">if</span> (i.operands.address &lt;= self.current_row.offset) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L479"> <span class="tok-comment">// TODO: Check cie.segment_selector_size != 0 for DWARFV4</span> </span> <span class="line" id="L480"> self.current_row.offset = i.operands.address;</span> <span class="line" id="L481"> },</span> <span class="line" id="L482"> <span class="tok-kw">inline</span> .advance_loc,</span> <span class="line" id="L483"> .advance_loc1,</span> <span class="line" id="L484"> .advance_loc2,</span> <span class="line" id="L485"> .advance_loc4,</span> <span class="line" id="L486"> =&gt; |i| {</span> <span class="line" id="L487"> self.current_row.offset += i.operands.delta * cie.code_alignment_factor;</span> <span class="line" id="L488"> self.current_row.copy_on_write = <span class="tok-null">true</span>;</span> <span class="line" id="L489"> },</span> <span class="line" id="L490"> <span class="tok-kw">inline</span> .offset,</span> <span class="line" id="L491"> .offset_extended,</span> <span class="line" id="L492"> .offset_extended_sf,</span> <span class="line" id="L493"> =&gt; |i| {</span> <span class="line" id="L494"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L495"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L496"> column.rule = .{ .offset = <span class="tok-builtin">@as</span>(<span class="tok-type">i64</span>, <span class="tok-builtin">@intCast</span>(i.operands.offset)) * cie.data_alignment_factor };</span> <span class="line" id="L497"> },</span> <span class="line" id="L498"> <span class="tok-kw">inline</span> .restore,</span> <span class="line" id="L499"> .restore_extended,</span> <span class="line" id="L500"> =&gt; |i| {</span> <span class="line" id="L501"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L502"> <span class="tok-kw">if</span> (self.cie_row) |cie_row| {</span> <span class="line" id="L503"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L504"> column.rule = <span class="tok-kw">for</span> (self.rowColumns(cie_row)) |cie_column| {</span> <span class="line" id="L505"> <span class="tok-kw">if</span> (cie_column.register == i.operands.register) <span class="tok-kw">break</span> cie_column.rule;</span> <span class="line" id="L506"> } <span class="tok-kw">else</span> .{ .default = {} };</span> <span class="line" id="L507"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L508"> },</span> <span class="line" id="L509"> .nop =&gt; {},</span> <span class="line" id="L510"> .<span class="tok-null">undefined</span> =&gt; |i| {</span> <span class="line" id="L511"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L512"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L513"> column.rule = .{ .<span class="tok-null">undefined</span> = {} };</span> <span class="line" id="L514"> },</span> <span class="line" id="L515"> .same_value =&gt; |i| {</span> <span class="line" id="L516"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L517"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L518"> column.rule = .{ .same_value = {} };</span> <span class="line" id="L519"> },</span> <span class="line" id="L520"> .register =&gt; |i| {</span> <span class="line" id="L521"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L522"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L523"> column.rule = .{ .register = i.operands.target_register };</span> <span class="line" id="L524"> },</span> <span class="line" id="L525"> .remember_state =&gt; {</span> <span class="line" id="L526"> <span class="tok-kw">try</span> self.stack.append(allocator, self.current_row.columns);</span> <span class="line" id="L527"> self.current_row.copy_on_write = <span class="tok-null">true</span>;</span> <span class="line" id="L528"> },</span> <span class="line" id="L529"> .restore_state =&gt; {</span> <span class="line" id="L530"> <span class="tok-kw">const</span> restored_columns = self.stack.popOrNull() <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L531"> self.columns.shrinkRetainingCapacity(self.columns.items.len - self.current_row.columns.len);</span> <span class="line" id="L532"> <span class="tok-kw">try</span> self.columns.ensureUnusedCapacity(allocator, restored_columns.len);</span> <span class="line" id="L533"></span> <span class="line" id="L534"> self.current_row.columns.start = self.columns.items.len;</span> <span class="line" id="L535"> self.current_row.columns.len = restored_columns.len;</span> <span class="line" id="L536"> self.columns.appendSliceAssumeCapacity(self.columns.items[restored_columns.start..][<span class="tok-number">0</span>..restored_columns.len]);</span> <span class="line" id="L537"> },</span> <span class="line" id="L538"> .def_cfa =&gt; |i| {</span> <span class="line" id="L539"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L540"> self.current_row.cfa = .{</span> <span class="line" id="L541"> .register = i.operands.register,</span> <span class="line" id="L542"> .rule = .{ .val_offset = <span class="tok-builtin">@intCast</span>(i.operands.offset) },</span> <span class="line" id="L543"> };</span> <span class="line" id="L544"> },</span> <span class="line" id="L545"> .def_cfa_sf =&gt; |i| {</span> <span class="line" id="L546"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L547"> self.current_row.cfa = .{</span> <span class="line" id="L548"> .register = i.operands.register,</span> <span class="line" id="L549"> .rule = .{ .val_offset = i.operands.offset * cie.data_alignment_factor },</span> <span class="line" id="L550"> };</span> <span class="line" id="L551"> },</span> <span class="line" id="L552"> .def_cfa_register =&gt; |i| {</span> <span class="line" id="L553"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L554"> <span class="tok-kw">if</span> (self.current_row.cfa.register == <span class="tok-null">null</span> <span class="tok-kw">or</span> self.current_row.cfa.rule != .val_offset) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L555"> self.current_row.cfa.register = i.operands.register;</span> <span class="line" id="L556"> },</span> <span class="line" id="L557"> .def_cfa_offset =&gt; |i| {</span> <span class="line" id="L558"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L559"> <span class="tok-kw">if</span> (self.current_row.cfa.register == <span class="tok-null">null</span> <span class="tok-kw">or</span> self.current_row.cfa.rule != .val_offset) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L560"> self.current_row.cfa.rule = .{</span> <span class="line" id="L561"> .val_offset = <span class="tok-builtin">@intCast</span>(i.operands.offset),</span> <span class="line" id="L562"> };</span> <span class="line" id="L563"> },</span> <span class="line" id="L564"> .def_cfa_offset_sf =&gt; |i| {</span> <span class="line" id="L565"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L566"> <span class="tok-kw">if</span> (self.current_row.cfa.register == <span class="tok-null">null</span> <span class="tok-kw">or</span> self.current_row.cfa.rule != .val_offset) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidOperation;</span> <span class="line" id="L567"> self.current_row.cfa.rule = .{</span> <span class="line" id="L568"> .val_offset = i.operands.offset * cie.data_alignment_factor,</span> <span class="line" id="L569"> };</span> <span class="line" id="L570"> },</span> <span class="line" id="L571"> .def_cfa_expression =&gt; |i| {</span> <span class="line" id="L572"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L573"> self.current_row.cfa.register = <span class="tok-null">undefined</span>;</span> <span class="line" id="L574"> self.current_row.cfa.rule = .{</span> <span class="line" id="L575"> .expression = i.operands.block,</span> <span class="line" id="L576"> };</span> <span class="line" id="L577"> },</span> <span class="line" id="L578"> .expression =&gt; |i| {</span> <span class="line" id="L579"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L580"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L581"> column.rule = .{</span> <span class="line" id="L582"> .expression = i.operands.block,</span> <span class="line" id="L583"> };</span> <span class="line" id="L584"> },</span> <span class="line" id="L585"> .val_offset =&gt; |i| {</span> <span class="line" id="L586"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L587"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L588"> column.rule = .{</span> <span class="line" id="L589"> .val_offset = <span class="tok-builtin">@as</span>(<span class="tok-type">i64</span>, <span class="tok-builtin">@intCast</span>(i.operands.offset)) * cie.data_alignment_factor,</span> <span class="line" id="L590"> };</span> <span class="line" id="L591"> },</span> <span class="line" id="L592"> .val_offset_sf =&gt; |i| {</span> <span class="line" id="L593"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L594"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L595"> column.rule = .{</span> <span class="line" id="L596"> .val_offset = i.operands.offset * cie.data_alignment_factor,</span> <span class="line" id="L597"> };</span> <span class="line" id="L598"> },</span> <span class="line" id="L599"> .val_expression =&gt; |i| {</span> <span class="line" id="L600"> <span class="tok-kw">try</span> self.resolveCopyOnWrite(allocator);</span> <span class="line" id="L601"> <span class="tok-kw">const</span> column = <span class="tok-kw">try</span> self.getOrAddColumn(allocator, i.operands.register);</span> <span class="line" id="L602"> column.rule = .{</span> <span class="line" id="L603"> .val_expression = i.operands.block,</span> <span class="line" id="L604"> };</span> <span class="line" id="L605"> },</span> <span class="line" id="L606"> }</span> <span class="line" id="L607"></span> <span class="line" id="L608"> <span class="tok-kw">return</span> prev_row;</span> <span class="line" id="L609"> }</span> <span class="line" id="L610">};</span> <span class="line" id="L611"></span> </code></pre></body> </html>
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/dwarf/TAG.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>dwarf/TAG.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> padding = <span class="tok-number">0x00</span>;</span> <span class="line" id="L2"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> array_type = <span class="tok-number">0x01</span>;</span> <span class="line" id="L3"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> class_type = <span class="tok-number">0x02</span>;</span> <span class="line" id="L4"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> entry_point = <span class="tok-number">0x03</span>;</span> <span class="line" id="L5"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> enumeration_type = <span class="tok-number">0x04</span>;</span> <span class="line" id="L6"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> formal_parameter = <span class="tok-number">0x05</span>;</span> <span class="line" id="L7"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> imported_declaration = <span class="tok-number">0x08</span>;</span> <span class="line" id="L8"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> label = <span class="tok-number">0x0a</span>;</span> <span class="line" id="L9"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> lexical_block = <span class="tok-number">0x0b</span>;</span> <span class="line" id="L10"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> member = <span class="tok-number">0x0d</span>;</span> <span class="line" id="L11"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> pointer_type = <span class="tok-number">0x0f</span>;</span> <span class="line" id="L12"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> reference_type = <span class="tok-number">0x10</span>;</span> <span class="line" id="L13"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> compile_unit = <span class="tok-number">0x11</span>;</span> <span class="line" id="L14"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> string_type = <span class="tok-number">0x12</span>;</span> <span class="line" id="L15"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> structure_type = <span class="tok-number">0x13</span>;</span> <span class="line" id="L16"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> subroutine = <span class="tok-number">0x14</span>;</span> <span class="line" id="L17"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> subroutine_type = <span class="tok-number">0x15</span>;</span> <span class="line" id="L18"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> typedef = <span class="tok-number">0x16</span>;</span> <span class="line" id="L19"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> union_type = <span class="tok-number">0x17</span>;</span> <span class="line" id="L20"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unspecified_parameters = <span class="tok-number">0x18</span>;</span> <span class="line" id="L21"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> variant = <span class="tok-number">0x19</span>;</span> <span class="line" id="L22"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> common_block = <span class="tok-number">0x1a</span>;</span> <span class="line" id="L23"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> common_inclusion = <span class="tok-number">0x1b</span>;</span> <span class="line" id="L24"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> inheritance = <span class="tok-number">0x1c</span>;</span> <span class="line" id="L25"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> inlined_subroutine = <span class="tok-number">0x1d</span>;</span> <span class="line" id="L26"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> module = <span class="tok-number">0x1e</span>;</span> <span class="line" id="L27"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ptr_to_member_type = <span class="tok-number">0x1f</span>;</span> <span class="line" id="L28"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> set_type = <span class="tok-number">0x20</span>;</span> <span class="line" id="L29"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> subrange_type = <span class="tok-number">0x21</span>;</span> <span class="line" id="L30"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> with_stmt = <span class="tok-number">0x22</span>;</span> <span class="line" id="L31"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> access_declaration = <span class="tok-number">0x23</span>;</span> <span class="line" id="L32"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> base_type = <span class="tok-number">0x24</span>;</span> <span class="line" id="L33"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> catch_block = <span class="tok-number">0x25</span>;</span> <span class="line" id="L34"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> const_type = <span class="tok-number">0x26</span>;</span> <span class="line" id="L35"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> constant = <span class="tok-number">0x27</span>;</span> <span class="line" id="L36"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> enumerator = <span class="tok-number">0x28</span>;</span> <span class="line" id="L37"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> file_type = <span class="tok-number">0x29</span>;</span> <span class="line" id="L38"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> friend = <span class="tok-number">0x2a</span>;</span> <span class="line" id="L39"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> namelist = <span class="tok-number">0x2b</span>;</span> <span class="line" id="L40"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> namelist_item = <span class="tok-number">0x2c</span>;</span> <span class="line" id="L41"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> packed_type = <span class="tok-number">0x2d</span>;</span> <span class="line" id="L42"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> subprogram = <span class="tok-number">0x2e</span>;</span> <span class="line" id="L43"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> template_type_param = <span class="tok-number">0x2f</span>;</span> <span class="line" id="L44"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> template_value_param = <span class="tok-number">0x30</span>;</span> <span class="line" id="L45"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> thrown_type = <span class="tok-number">0x31</span>;</span> <span class="line" id="L46"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> try_block = <span class="tok-number">0x32</span>;</span> <span class="line" id="L47"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> variant_part = <span class="tok-number">0x33</span>;</span> <span class="line" id="L48"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> variable = <span class="tok-number">0x34</span>;</span> <span class="line" id="L49"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> volatile_type = <span class="tok-number">0x35</span>;</span> <span class="line" id="L50"></span> <span class="line" id="L51"><span class="tok-comment">// DWARF 3</span> </span> <span class="line" id="L52"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> dwarf_procedure = <span class="tok-number">0x36</span>;</span> <span class="line" id="L53"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> restrict_type = <span class="tok-number">0x37</span>;</span> <span class="line" id="L54"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> interface_type = <span class="tok-number">0x38</span>;</span> <span class="line" id="L55"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> namespace = <span class="tok-number">0x39</span>;</span> <span class="line" id="L56"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> imported_module = <span class="tok-number">0x3a</span>;</span> <span class="line" id="L57"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unspecified_type = <span class="tok-number">0x3b</span>;</span> <span class="line" id="L58"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> partial_unit = <span class="tok-number">0x3c</span>;</span> <span class="line" id="L59"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> imported_unit = <span class="tok-number">0x3d</span>;</span> <span class="line" id="L60"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> condition = <span class="tok-number">0x3f</span>;</span> <span class="line" id="L61"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> shared_type = <span class="tok-number">0x40</span>;</span> <span class="line" id="L62"></span> <span class="line" id="L63"><span class="tok-comment">// DWARF 4</span> </span> <span class="line" id="L64"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> type_unit = <span class="tok-number">0x41</span>;</span> <span class="line" id="L65"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> rvalue_reference_type = <span class="tok-number">0x42</span>;</span> <span class="line" id="L66"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> template_alias = <span class="tok-number">0x43</span>;</span> <span class="line" id="L67"></span> <span class="line" id="L68"><span class="tok-comment">// DWARF 5</span> </span> <span class="line" id="L69"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> coarray_type = <span class="tok-number">0x44</span>;</span> <span class="line" id="L70"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> generic_subrange = <span class="tok-number">0x45</span>;</span> <span class="line" id="L71"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> dynamic_type = <span class="tok-number">0x46</span>;</span> <span class="line" id="L72"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> atomic_type = <span class="tok-number">0x47</span>;</span> <span class="line" id="L73"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> call_site = <span class="tok-number">0x48</span>;</span> <span class="line" id="L74"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> call_site_parameter = <span class="tok-number">0x49</span>;</span> <span class="line" id="L75"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> skeleton_unit = <span class="tok-number">0x4a</span>;</span> <span class="line" id="L76"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> immutable_type = <span class="tok-number">0x4b</span>;</span> <span class="line" id="L77"></span> <span class="line" id="L78"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_user = <span class="tok-number">0x4080</span>;</span> <span class="line" id="L79"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_user = <span class="tok-number">0xffff</span>;</span> <span class="line" id="L80"></span> <span class="line" id="L81"><span class="tok-comment">// SGI/MIPS Extensions.</span> </span> <span class="line" id="L82"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> MIPS_loop = <span class="tok-number">0x4081</span>;</span> <span class="line" id="L83"></span> <span class="line" id="L84"><span class="tok-comment">// HP extensions. See: ftp://ftp.hp.com/pub/lang/tools/WDB/wdb-4.0.tar.gz .</span> </span> <span class="line" id="L85"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_array_descriptor = <span class="tok-number">0x4090</span>;</span> <span class="line" id="L86"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Bliss_field = <span class="tok-number">0x4091</span>;</span> <span class="line" id="L87"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Bliss_field_set = <span class="tok-number">0x4092</span>;</span> <span class="line" id="L88"></span> <span class="line" id="L89"><span class="tok-comment">// GNU extensions.</span> </span> <span class="line" id="L90"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> format_label = <span class="tok-number">0x4101</span>; <span class="tok-comment">// For FORTRAN 77 and Fortran 90.</span> </span> <span class="line" id="L91"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> function_template = <span class="tok-number">0x4102</span>; <span class="tok-comment">// For C++.</span> </span> <span class="line" id="L92"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> class_template = <span class="tok-number">0x4103</span>; <span class="tok-comment">//For C++.</span> </span> <span class="line" id="L93"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_BINCL = <span class="tok-number">0x4104</span>;</span> <span class="line" id="L94"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_EINCL = <span class="tok-number">0x4105</span>;</span> <span class="line" id="L95"></span> <span class="line" id="L96"><span class="tok-comment">// Template template parameter.</span> </span> <span class="line" id="L97"><span class="tok-comment">// See http://gcc.gnu.org/wiki/TemplateParmsDwarf .</span> </span> <span class="line" id="L98"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_template_template_param = <span class="tok-number">0x4106</span>;</span> <span class="line" id="L99"></span> <span class="line" id="L100"><span class="tok-comment">// Template parameter pack extension = specified at</span> </span> <span class="line" id="L101"><span class="tok-comment">// http://wiki.dwarfstd.org/index.php?title=C%2B%2B0x:_Variadic_templates</span> </span> <span class="line" id="L102"><span class="tok-comment">// The values of these two TAGS are in the DW_TAG_GNU_* space until the tags</span> </span> <span class="line" id="L103"><span class="tok-comment">// are properly part of DWARF 5.</span> </span> <span class="line" id="L104"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_template_parameter_pack = <span class="tok-number">0x4107</span>;</span> <span class="line" id="L105"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_formal_parameter_pack = <span class="tok-number">0x4108</span>;</span> <span class="line" id="L106"><span class="tok-comment">// The GNU call site extension = specified at</span> </span> <span class="line" id="L107"><span class="tok-comment">// http://www.dwarfstd.org/ShowIssue.php?issue=100909.2&amp;type=open .</span> </span> <span class="line" id="L108"><span class="tok-comment">// The values of these two TAGS are in the DW_TAG_GNU_* space until the tags</span> </span> <span class="line" id="L109"><span class="tok-comment">// are properly part of DWARF 5.</span> </span> <span class="line" id="L110"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_call_site = <span class="tok-number">0x4109</span>;</span> <span class="line" id="L111"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> GNU_call_site_parameter = <span class="tok-number">0x410a</span>;</span> <span class="line" id="L112"><span class="tok-comment">// Extensions for UPC. See: http://dwarfstd.org/doc/DWARF4.pdf.</span> </span> <span class="line" id="L113"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> upc_shared_type = <span class="tok-number">0x8765</span>;</span> <span class="line" id="L114"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> upc_strict_type = <span class="tok-number">0x8766</span>;</span> <span class="line" id="L115"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> upc_relaxed_type = <span class="tok-number">0x8767</span>;</span> <span class="line" id="L116"><span class="tok-comment">// PGI (STMicroelectronics; extensions. No documentation available.</span> </span> <span class="line" id="L117"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> PGI_kanji_type = <span class="tok-number">0xA000</span>;</span> <span class="line" id="L118"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> PGI_interface_block = <span class="tok-number">0xA020</span>;</span> <span class="line" id="L119"></span> </code></pre></body> </html>
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/dwarf/ATE.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>dwarf/ATE.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> @&quot;void&quot; = <span class="tok-number">0x0</span>;</span> <span class="line" id="L2"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> address = <span class="tok-number">0x1</span>;</span> <span class="line" id="L3"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> boolean = <span class="tok-number">0x2</span>;</span> <span class="line" id="L4"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> complex_float = <span class="tok-number">0x3</span>;</span> <span class="line" id="L5"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> float = <span class="tok-number">0x4</span>;</span> <span class="line" id="L6"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> signed = <span class="tok-number">0x5</span>;</span> <span class="line" id="L7"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> signed_char = <span class="tok-number">0x6</span>;</span> <span class="line" id="L8"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unsigned = <span class="tok-number">0x7</span>;</span> <span class="line" id="L9"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unsigned_char = <span class="tok-number">0x8</span>;</span> <span class="line" id="L10"></span> <span class="line" id="L11"><span class="tok-comment">// DWARF 3.</span> </span> <span class="line" id="L12"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> imaginary_float = <span class="tok-number">0x9</span>;</span> <span class="line" id="L13"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> packed_decimal = <span class="tok-number">0xa</span>;</span> <span class="line" id="L14"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> numeric_string = <span class="tok-number">0xb</span>;</span> <span class="line" id="L15"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> edited = <span class="tok-number">0xc</span>;</span> <span class="line" id="L16"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> signed_fixed = <span class="tok-number">0xd</span>;</span> <span class="line" id="L17"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unsigned_fixed = <span class="tok-number">0xe</span>;</span> <span class="line" id="L18"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> decimal_float = <span class="tok-number">0xf</span>;</span> <span class="line" id="L19"></span> <span class="line" id="L20"><span class="tok-comment">// DWARF 4.</span> </span> <span class="line" id="L21"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> UTF = <span class="tok-number">0x10</span>;</span> <span class="line" id="L22"></span> <span class="line" id="L23"><span class="tok-comment">// DWARF 5.</span> </span> <span class="line" id="L24"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> UCS = <span class="tok-number">0x11</span>;</span> <span class="line" id="L25"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ASCII = <span class="tok-number">0x12</span>;</span> <span class="line" id="L26"></span> <span class="line" id="L27"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_user = <span class="tok-number">0x80</span>;</span> <span class="line" id="L28"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_user = <span class="tok-number">0xff</span>;</span> <span class="line" id="L29"></span> <span class="line" id="L30"><span class="tok-comment">// HP extensions.</span> </span> <span class="line" id="L31"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_float80 = <span class="tok-number">0x80</span>; <span class="tok-comment">// Floating-point (80 bit).</span> </span> <span class="line" id="L32"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_complex_float80 = <span class="tok-number">0x81</span>; <span class="tok-comment">// Complex floating-point (80 bit).</span> </span> <span class="line" id="L33"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_float128 = <span class="tok-number">0x82</span>; <span class="tok-comment">// Floating-point (128 bit).</span> </span> <span class="line" id="L34"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_complex_float128 = <span class="tok-number">0x83</span>; <span class="tok-comment">// Complex fp (128 bit).</span> </span> <span class="line" id="L35"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_floathpintel = <span class="tok-number">0x84</span>; <span class="tok-comment">// Floating-point (82 bit IA64).</span> </span> <span class="line" id="L36"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_imaginary_float80 = <span class="tok-number">0x85</span>;</span> <span class="line" id="L37"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_imaginary_float128 = <span class="tok-number">0x86</span>;</span> <span class="line" id="L38"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_VAX_float = <span class="tok-number">0x88</span>; <span class="tok-comment">// F or G floating.</span> </span> <span class="line" id="L39"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_VAX_float_d = <span class="tok-number">0x89</span>; <span class="tok-comment">// D floating.</span> </span> <span class="line" id="L40"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_packed_decimal = <span class="tok-number">0x8a</span>; <span class="tok-comment">// Cobol.</span> </span> <span class="line" id="L41"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_zoned_decimal = <span class="tok-number">0x8b</span>; <span class="tok-comment">// Cobol.</span> </span> <span class="line" id="L42"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_edited = <span class="tok-number">0x8c</span>; <span class="tok-comment">// Cobol.</span> </span> <span class="line" id="L43"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_signed_fixed = <span class="tok-number">0x8d</span>; <span class="tok-comment">// Cobol.</span> </span> <span class="line" id="L44"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_unsigned_fixed = <span class="tok-number">0x8e</span>; <span class="tok-comment">// Cobol.</span> </span> <span class="line" id="L45"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_VAX_complex_float = <span class="tok-number">0x8f</span>; <span class="tok-comment">// F or G floating complex.</span> </span> <span class="line" id="L46"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_VAX_complex_float_d = <span class="tok-number">0x90</span>; <span class="tok-comment">// D floating complex.</span> </span> <span class="line" id="L47"></span> </code></pre></body> </html>
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/dwarf/LANG.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>dwarf/LANG.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C89 = <span class="tok-number">0x0001</span>;</span> <span class="line" id="L2"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C = <span class="tok-number">0x0002</span>;</span> <span class="line" id="L3"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Ada83 = <span class="tok-number">0x0003</span>;</span> <span class="line" id="L4"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C_plus_plus = <span class="tok-number">0x0004</span>;</span> <span class="line" id="L5"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Cobol74 = <span class="tok-number">0x0005</span>;</span> <span class="line" id="L6"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Cobol85 = <span class="tok-number">0x0006</span>;</span> <span class="line" id="L7"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Fortran77 = <span class="tok-number">0x0007</span>;</span> <span class="line" id="L8"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Fortran90 = <span class="tok-number">0x0008</span>;</span> <span class="line" id="L9"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Pascal83 = <span class="tok-number">0x0009</span>;</span> <span class="line" id="L10"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Modula2 = <span class="tok-number">0x000a</span>;</span> <span class="line" id="L11"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Java = <span class="tok-number">0x000b</span>;</span> <span class="line" id="L12"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C99 = <span class="tok-number">0x000c</span>;</span> <span class="line" id="L13"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Ada95 = <span class="tok-number">0x000d</span>;</span> <span class="line" id="L14"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Fortran95 = <span class="tok-number">0x000e</span>;</span> <span class="line" id="L15"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> PLI = <span class="tok-number">0x000f</span>;</span> <span class="line" id="L16"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ObjC = <span class="tok-number">0x0010</span>;</span> <span class="line" id="L17"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ObjC_plus_plus = <span class="tok-number">0x0011</span>;</span> <span class="line" id="L18"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> UPC = <span class="tok-number">0x0012</span>;</span> <span class="line" id="L19"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> D = <span class="tok-number">0x0013</span>;</span> <span class="line" id="L20"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Python = <span class="tok-number">0x0014</span>;</span> <span class="line" id="L21"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> OpenCL = <span class="tok-number">0x0015</span>;</span> <span class="line" id="L22"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Go = <span class="tok-number">0x0016</span>;</span> <span class="line" id="L23"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Modula3 = <span class="tok-number">0x0017</span>;</span> <span class="line" id="L24"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Haskell = <span class="tok-number">0x0018</span>;</span> <span class="line" id="L25"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C_plus_plus_03 = <span class="tok-number">0x0019</span>;</span> <span class="line" id="L26"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C_plus_plus_11 = <span class="tok-number">0x001a</span>;</span> <span class="line" id="L27"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> OCaml = <span class="tok-number">0x001b</span>;</span> <span class="line" id="L28"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Rust = <span class="tok-number">0x001c</span>;</span> <span class="line" id="L29"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C11 = <span class="tok-number">0x001d</span>;</span> <span class="line" id="L30"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Swift = <span class="tok-number">0x001e</span>;</span> <span class="line" id="L31"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Julia = <span class="tok-number">0x001f</span>;</span> <span class="line" id="L32"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Dylan = <span class="tok-number">0x0020</span>;</span> <span class="line" id="L33"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> C_plus_plus_14 = <span class="tok-number">0x0021</span>;</span> <span class="line" id="L34"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Fortran03 = <span class="tok-number">0x0022</span>;</span> <span class="line" id="L35"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Fortran08 = <span class="tok-number">0x0023</span>;</span> <span class="line" id="L36"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> RenderScript = <span class="tok-number">0x0024</span>;</span> <span class="line" id="L37"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> BLISS = <span class="tok-number">0x0025</span>;</span> <span class="line" id="L38"></span> <span class="line" id="L39"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> lo_user = <span class="tok-number">0x8000</span>;</span> <span class="line" id="L40"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> hi_user = <span class="tok-number">0xffff</span>;</span> <span class="line" id="L41"></span> <span class="line" id="L42"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Mips_Assembler = <span class="tok-number">0x8001</span>;</span> <span class="line" id="L43"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Upc = <span class="tok-number">0x8765</span>;</span> <span class="line" id="L44"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Bliss = <span class="tok-number">0x8003</span>;</span> <span class="line" id="L45"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Basic91 = <span class="tok-number">0x8004</span>;</span> <span class="line" id="L46"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Pascal91 = <span class="tok-number">0x8005</span>;</span> <span class="line" id="L47"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_IMacro = <span class="tok-number">0x8006</span>;</span> <span class="line" id="L48"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> HP_Assembler = <span class="tok-number">0x8007</span>;</span> <span class="line" id="L49"></span> </code></pre></body> </html>
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/dwarf/expressions.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>dwarf/expressions.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-kw">const</span> std = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;std&quot;</span>);</span> <span class="line" id="L2"><span class="tok-kw">const</span> builtin = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;builtin&quot;</span>);</span> <span class="line" id="L3"><span class="tok-kw">const</span> OP = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;OP.zig&quot;</span>);</span> <span class="line" id="L4"><span class="tok-kw">const</span> leb = std.leb;</span> <span class="line" id="L5"><span class="tok-kw">const</span> dwarf = std.dwarf;</span> <span class="line" id="L6"><span class="tok-kw">const</span> abi = dwarf.abi;</span> <span class="line" id="L7"><span class="tok-kw">const</span> mem = std.mem;</span> <span class="line" id="L8"><span class="tok-kw">const</span> assert = std.debug.assert;</span> <span class="line" id="L9"></span> <span class="line" id="L10"><span class="tok-comment">/// Expressions can be evaluated in different contexts, each requiring its own set of inputs.</span></span> <span class="line" id="L11"><span class="tok-comment">/// Callers should specify all the fields relevant to their context. If a field is required</span></span> <span class="line" id="L12"><span class="tok-comment">/// by the expression and it isn't in the context, error.IncompleteExpressionContext is returned.</span></span> <span class="line" id="L13"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ExpressionContext = <span class="tok-kw">struct</span> {</span> <span class="line" id="L14"> <span class="tok-comment">/// This expression is from a DWARF64 section</span></span> <span class="line" id="L15"> is_64: <span class="tok-type">bool</span> = <span class="tok-null">false</span>,</span> <span class="line" id="L16"></span> <span class="line" id="L17"> <span class="tok-comment">/// If specified, any addresses will pass through this function before being acccessed</span></span> <span class="line" id="L18"> isValidMemory: ?*<span class="tok-kw">const</span> <span class="tok-kw">fn</span> (address: <span class="tok-type">usize</span>) <span class="tok-type">bool</span> = <span class="tok-null">null</span>,</span> <span class="line" id="L19"></span> <span class="line" id="L20"> <span class="tok-comment">/// The compilation unit this expression relates to, if any</span></span> <span class="line" id="L21"> compile_unit: ?*<span class="tok-kw">const</span> dwarf.CompileUnit = <span class="tok-null">null</span>,</span> <span class="line" id="L22"></span> <span class="line" id="L23"> <span class="tok-comment">/// When evaluating a user-presented expression, this is the address of the object being evaluated</span></span> <span class="line" id="L24"> object_address: ?*<span class="tok-kw">const</span> <span class="tok-type">anyopaque</span> = <span class="tok-null">null</span>,</span> <span class="line" id="L25"></span> <span class="line" id="L26"> <span class="tok-comment">/// .debug_addr section</span></span> <span class="line" id="L27"> debug_addr: ?[]<span class="tok-kw">const</span> <span class="tok-type">u8</span> = <span class="tok-null">null</span>,</span> <span class="line" id="L28"></span> <span class="line" id="L29"> <span class="tok-comment">/// Thread context</span></span> <span class="line" id="L30"> thread_context: ?*std.debug.ThreadContext = <span class="tok-null">null</span>,</span> <span class="line" id="L31"> reg_context: ?abi.RegisterContext = <span class="tok-null">null</span>,</span> <span class="line" id="L32"></span> <span class="line" id="L33"> <span class="tok-comment">/// Call frame address, if in a CFI context</span></span> <span class="line" id="L34"> cfa: ?<span class="tok-type">usize</span> = <span class="tok-null">null</span>,</span> <span class="line" id="L35"></span> <span class="line" id="L36"> <span class="tok-comment">/// This expression is a sub-expression from an OP.entry_value instruction</span></span> <span class="line" id="L37"> entry_value_context: <span class="tok-type">bool</span> = <span class="tok-null">false</span>,</span> <span class="line" id="L38">};</span> <span class="line" id="L39"></span> <span class="line" id="L40"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ExpressionOptions = <span class="tok-kw">struct</span> {</span> <span class="line" id="L41"> <span class="tok-comment">/// The address size of the target architecture</span></span> <span class="line" id="L42"> addr_size: <span class="tok-type">u8</span> = <span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>),</span> <span class="line" id="L43"></span> <span class="line" id="L44"> <span class="tok-comment">/// Endianess of the target architecture</span></span> <span class="line" id="L45"> endian: std.builtin.Endian = builtin.target.cpu.arch.endian(),</span> <span class="line" id="L46"></span> <span class="line" id="L47"> <span class="tok-comment">/// Restrict the stack machine to a subset of opcodes used in call frame instructions</span></span> <span class="line" id="L48"> call_frame_context: <span class="tok-type">bool</span> = <span class="tok-null">false</span>,</span> <span class="line" id="L49">};</span> <span class="line" id="L50"></span> <span class="line" id="L51"><span class="tok-comment">// Explcitly defined to support executing sub-expressions</span> </span> <span class="line" id="L52"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ExpressionError = <span class="tok-kw">error</span>{</span> <span class="line" id="L53"> UnimplementedExpressionCall,</span> <span class="line" id="L54"> UnimplementedOpcode,</span> <span class="line" id="L55"> UnimplementedUserOpcode,</span> <span class="line" id="L56"> UnimplementedTypedComparison,</span> <span class="line" id="L57"> UnimplementedTypeConversion,</span> <span class="line" id="L58"></span> <span class="line" id="L59"> UnknownExpressionOpcode,</span> <span class="line" id="L60"></span> <span class="line" id="L61"> IncompleteExpressionContext,</span> <span class="line" id="L62"></span> <span class="line" id="L63"> InvalidCFAOpcode,</span> <span class="line" id="L64"> InvalidExpression,</span> <span class="line" id="L65"> InvalidFrameBase,</span> <span class="line" id="L66"> InvalidIntegralTypeSize,</span> <span class="line" id="L67"> InvalidRegister,</span> <span class="line" id="L68"> InvalidSubExpression,</span> <span class="line" id="L69"> InvalidTypeLength,</span> <span class="line" id="L70"></span> <span class="line" id="L71"> TruncatedIntegralType,</span> <span class="line" id="L72">} || abi.AbiError || <span class="tok-kw">error</span>{ EndOfStream, Overflow, OutOfMemory, DivisionByZero };</span> <span class="line" id="L73"></span> <span class="line" id="L74"><span class="tok-comment">/// A stack machine that can decode and run DWARF expressions.</span></span> <span class="line" id="L75"><span class="tok-comment">/// Expressions can be decoded for non-native address size and endianness,</span></span> <span class="line" id="L76"><span class="tok-comment">/// but can only be executed if the current target matches the configuration.</span></span> <span class="line" id="L77"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">StackMachine</span>(<span class="tok-kw">comptime</span> options: ExpressionOptions) <span class="tok-type">type</span> {</span> <span class="line" id="L78"> <span class="tok-kw">const</span> addr_type = <span class="tok-kw">switch</span> (options.addr_size) {</span> <span class="line" id="L79"> <span class="tok-number">2</span> =&gt; <span class="tok-type">u16</span>,</span> <span class="line" id="L80"> <span class="tok-number">4</span> =&gt; <span class="tok-type">u32</span>,</span> <span class="line" id="L81"> <span class="tok-number">8</span> =&gt; <span class="tok-type">u64</span>,</span> <span class="line" id="L82"> <span class="tok-kw">else</span> =&gt; <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Unsupported address size of &quot;</span> ++ options.addr_size),</span> <span class="line" id="L83"> };</span> <span class="line" id="L84"></span> <span class="line" id="L85"> <span class="tok-kw">const</span> addr_type_signed = <span class="tok-kw">switch</span> (options.addr_size) {</span> <span class="line" id="L86"> <span class="tok-number">2</span> =&gt; <span class="tok-type">i16</span>,</span> <span class="line" id="L87"> <span class="tok-number">4</span> =&gt; <span class="tok-type">i32</span>,</span> <span class="line" id="L88"> <span class="tok-number">8</span> =&gt; <span class="tok-type">i64</span>,</span> <span class="line" id="L89"> <span class="tok-kw">else</span> =&gt; <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Unsupported address size of &quot;</span> ++ options.addr_size),</span> <span class="line" id="L90"> };</span> <span class="line" id="L91"></span> <span class="line" id="L92"> <span class="tok-kw">return</span> <span class="tok-kw">struct</span> {</span> <span class="line" id="L93"> <span class="tok-kw">const</span> Self = <span class="tok-builtin">@This</span>();</span> <span class="line" id="L94"></span> <span class="line" id="L95"> <span class="tok-kw">const</span> Operand = <span class="tok-kw">union</span>(<span class="tok-kw">enum</span>) {</span> <span class="line" id="L96"> generic: addr_type,</span> <span class="line" id="L97"> register: <span class="tok-type">u8</span>,</span> <span class="line" id="L98"> type_size: <span class="tok-type">u8</span>,</span> <span class="line" id="L99"> branch_offset: <span class="tok-type">i16</span>,</span> <span class="line" id="L100"> base_register: <span class="tok-kw">struct</span> {</span> <span class="line" id="L101"> base_register: <span class="tok-type">u8</span>,</span> <span class="line" id="L102"> offset: <span class="tok-type">i64</span>,</span> <span class="line" id="L103"> },</span> <span class="line" id="L104"> composite_location: <span class="tok-kw">struct</span> {</span> <span class="line" id="L105"> size: <span class="tok-type">u64</span>,</span> <span class="line" id="L106"> offset: <span class="tok-type">i64</span>,</span> <span class="line" id="L107"> },</span> <span class="line" id="L108"> block: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L109"> register_type: <span class="tok-kw">struct</span> {</span> <span class="line" id="L110"> register: <span class="tok-type">u8</span>,</span> <span class="line" id="L111"> type_offset: addr_type,</span> <span class="line" id="L112"> },</span> <span class="line" id="L113"> const_type: <span class="tok-kw">struct</span> {</span> <span class="line" id="L114"> type_offset: addr_type,</span> <span class="line" id="L115"> value_bytes: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L116"> },</span> <span class="line" id="L117"> deref_type: <span class="tok-kw">struct</span> {</span> <span class="line" id="L118"> size: <span class="tok-type">u8</span>,</span> <span class="line" id="L119"> type_offset: addr_type,</span> <span class="line" id="L120"> },</span> <span class="line" id="L121"> };</span> <span class="line" id="L122"></span> <span class="line" id="L123"> <span class="tok-kw">const</span> Value = <span class="tok-kw">union</span>(<span class="tok-kw">enum</span>) {</span> <span class="line" id="L124"> generic: addr_type,</span> <span class="line" id="L125"></span> <span class="line" id="L126"> <span class="tok-comment">// Typed value with a maximum size of a register</span> </span> <span class="line" id="L127"> regval_type: <span class="tok-kw">struct</span> {</span> <span class="line" id="L128"> <span class="tok-comment">// Offset of DW_TAG_base_type DIE</span> </span> <span class="line" id="L129"> type_offset: addr_type,</span> <span class="line" id="L130"> type_size: <span class="tok-type">u8</span>,</span> <span class="line" id="L131"> value: addr_type,</span> <span class="line" id="L132"> },</span> <span class="line" id="L133"></span> <span class="line" id="L134"> <span class="tok-comment">// Typed value specified directly in the instruction stream</span> </span> <span class="line" id="L135"> const_type: <span class="tok-kw">struct</span> {</span> <span class="line" id="L136"> <span class="tok-comment">// Offset of DW_TAG_base_type DIE</span> </span> <span class="line" id="L137"> type_offset: addr_type,</span> <span class="line" id="L138"> <span class="tok-comment">// Backed by the instruction stream</span> </span> <span class="line" id="L139"> value_bytes: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L140"> },</span> <span class="line" id="L141"></span> <span class="line" id="L142"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">asIntegral</span>(self: Value) !addr_type {</span> <span class="line" id="L143"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (self) {</span> <span class="line" id="L144"> .generic =&gt; |v| v,</span> <span class="line" id="L145"></span> <span class="line" id="L146"> <span class="tok-comment">// TODO: For these two prongs, look up the type and assert it's integral?</span> </span> <span class="line" id="L147"> .regval_type =&gt; |regval_type| regval_type.value,</span> <span class="line" id="L148"> .const_type =&gt; |const_type| {</span> <span class="line" id="L149"> <span class="tok-kw">const</span> value: <span class="tok-type">u64</span> = <span class="tok-kw">switch</span> (const_type.value_bytes.len) {</span> <span class="line" id="L150"> <span class="tok-number">1</span> =&gt; mem.readIntSliceNative(<span class="tok-type">u8</span>, const_type.value_bytes),</span> <span class="line" id="L151"> <span class="tok-number">2</span> =&gt; mem.readIntSliceNative(<span class="tok-type">u16</span>, const_type.value_bytes),</span> <span class="line" id="L152"> <span class="tok-number">4</span> =&gt; mem.readIntSliceNative(<span class="tok-type">u32</span>, const_type.value_bytes),</span> <span class="line" id="L153"> <span class="tok-number">8</span> =&gt; mem.readIntSliceNative(<span class="tok-type">u64</span>, const_type.value_bytes),</span> <span class="line" id="L154"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidIntegralTypeSize,</span> <span class="line" id="L155"> };</span> <span class="line" id="L156"></span> <span class="line" id="L157"> <span class="tok-kw">return</span> std.math.cast(addr_type, value) <span class="tok-kw">orelse</span> <span class="tok-kw">error</span>.TruncatedIntegralType;</span> <span class="line" id="L158"> },</span> <span class="line" id="L159"> };</span> <span class="line" id="L160"> }</span> <span class="line" id="L161"> };</span> <span class="line" id="L162"></span> <span class="line" id="L163"> stack: std.ArrayListUnmanaged(Value) = .{},</span> <span class="line" id="L164"></span> <span class="line" id="L165"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">reset</span>(self: *Self) <span class="tok-type">void</span> {</span> <span class="line" id="L166"> self.stack.clearRetainingCapacity();</span> <span class="line" id="L167"> }</span> <span class="line" id="L168"></span> <span class="line" id="L169"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">deinit</span>(self: *Self, allocator: std.mem.Allocator) <span class="tok-type">void</span> {</span> <span class="line" id="L170"> self.stack.deinit(allocator);</span> <span class="line" id="L171"> }</span> <span class="line" id="L172"></span> <span class="line" id="L173"> <span class="tok-kw">fn</span> <span class="tok-fn">generic</span>(value: <span class="tok-kw">anytype</span>) Operand {</span> <span class="line" id="L174"> <span class="tok-kw">const</span> int_info = <span class="tok-builtin">@typeInfo</span>(<span class="tok-builtin">@TypeOf</span>(value)).Int;</span> <span class="line" id="L175"> <span class="tok-kw">if</span> (<span class="tok-builtin">@sizeOf</span>(<span class="tok-builtin">@TypeOf</span>(value)) &gt; options.addr_size) {</span> <span class="line" id="L176"> <span class="tok-kw">return</span> .{ .generic = <span class="tok-kw">switch</span> (int_info.signedness) {</span> <span class="line" id="L177"> .signed =&gt; <span class="tok-builtin">@bitCast</span>(<span class="tok-builtin">@as</span>(addr_type_signed, <span class="tok-builtin">@truncate</span>(value))),</span> <span class="line" id="L178"> .unsigned =&gt; <span class="tok-builtin">@truncate</span>(value),</span> <span class="line" id="L179"> } };</span> <span class="line" id="L180"> } <span class="tok-kw">else</span> {</span> <span class="line" id="L181"> <span class="tok-kw">return</span> .{ .generic = <span class="tok-kw">switch</span> (int_info.signedness) {</span> <span class="line" id="L182"> .signed =&gt; <span class="tok-builtin">@bitCast</span>(<span class="tok-builtin">@as</span>(addr_type_signed, <span class="tok-builtin">@intCast</span>(value))),</span> <span class="line" id="L183"> .unsigned =&gt; <span class="tok-builtin">@intCast</span>(value),</span> <span class="line" id="L184"> } };</span> <span class="line" id="L185"> }</span> <span class="line" id="L186"> }</span> <span class="line" id="L187"></span> <span class="line" id="L188"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">readOperand</span>(stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>), opcode: <span class="tok-type">u8</span>, context: ExpressionContext) !?Operand {</span> <span class="line" id="L189"> <span class="tok-kw">const</span> reader = stream.reader();</span> <span class="line" id="L190"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L191"> OP.addr =&gt; generic(<span class="tok-kw">try</span> reader.readInt(addr_type, options.endian)),</span> <span class="line" id="L192"> OP.call_ref =&gt; <span class="tok-kw">if</span> (context.is_64)</span> <span class="line" id="L193"> generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u64</span>, options.endian))</span> <span class="line" id="L194"> <span class="tok-kw">else</span></span> <span class="line" id="L195"> generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u32</span>, options.endian)),</span> <span class="line" id="L196"> OP.const1u,</span> <span class="line" id="L197"> OP.pick,</span> <span class="line" id="L198"> =&gt; generic(<span class="tok-kw">try</span> reader.readByte()),</span> <span class="line" id="L199"> OP.deref_size,</span> <span class="line" id="L200"> OP.xderef_size,</span> <span class="line" id="L201"> =&gt; .{ .type_size = <span class="tok-kw">try</span> reader.readByte() },</span> <span class="line" id="L202"> OP.const1s =&gt; generic(<span class="tok-kw">try</span> reader.readByteSigned()),</span> <span class="line" id="L203"> OP.const2u,</span> <span class="line" id="L204"> OP.call2,</span> <span class="line" id="L205"> =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u16</span>, options.endian)),</span> <span class="line" id="L206"> OP.call4 =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u32</span>, options.endian)),</span> <span class="line" id="L207"> OP.const2s =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">i16</span>, options.endian)),</span> <span class="line" id="L208"> OP.bra,</span> <span class="line" id="L209"> OP.skip,</span> <span class="line" id="L210"> =&gt; .{ .branch_offset = <span class="tok-kw">try</span> reader.readInt(<span class="tok-type">i16</span>, options.endian) },</span> <span class="line" id="L211"> OP.const4u =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u32</span>, options.endian)),</span> <span class="line" id="L212"> OP.const4s =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">i32</span>, options.endian)),</span> <span class="line" id="L213"> OP.const8u =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">u64</span>, options.endian)),</span> <span class="line" id="L214"> OP.const8s =&gt; generic(<span class="tok-kw">try</span> reader.readInt(<span class="tok-type">i64</span>, options.endian)),</span> <span class="line" id="L215"> OP.constu,</span> <span class="line" id="L216"> OP.plus_uconst,</span> <span class="line" id="L217"> OP.addrx,</span> <span class="line" id="L218"> OP.constx,</span> <span class="line" id="L219"> OP.convert,</span> <span class="line" id="L220"> OP.reinterpret,</span> <span class="line" id="L221"> =&gt; generic(<span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u64</span>, reader)),</span> <span class="line" id="L222"> OP.consts,</span> <span class="line" id="L223"> OP.fbreg,</span> <span class="line" id="L224"> =&gt; generic(<span class="tok-kw">try</span> leb.readILEB128(<span class="tok-type">i64</span>, reader)),</span> <span class="line" id="L225"> OP.lit0...OP.lit31 =&gt; |n| generic(n - OP.lit0),</span> <span class="line" id="L226"> OP.reg0...OP.reg31 =&gt; |n| .{ .register = n - OP.reg0 },</span> <span class="line" id="L227"> OP.breg0...OP.breg31 =&gt; |n| .{ .base_register = .{</span> <span class="line" id="L228"> .base_register = n - OP.breg0,</span> <span class="line" id="L229"> .offset = <span class="tok-kw">try</span> leb.readILEB128(<span class="tok-type">i64</span>, reader),</span> <span class="line" id="L230"> } },</span> <span class="line" id="L231"> OP.regx =&gt; .{ .register = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader) },</span> <span class="line" id="L232"> OP.bregx =&gt; blk: {</span> <span class="line" id="L233"> <span class="tok-kw">const</span> base_register = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader);</span> <span class="line" id="L234"> <span class="tok-kw">const</span> offset = <span class="tok-kw">try</span> leb.readILEB128(<span class="tok-type">i64</span>, reader);</span> <span class="line" id="L235"> <span class="tok-kw">break</span> :blk .{ .base_register = .{</span> <span class="line" id="L236"> .base_register = base_register,</span> <span class="line" id="L237"> .offset = offset,</span> <span class="line" id="L238"> } };</span> <span class="line" id="L239"> },</span> <span class="line" id="L240"> OP.regval_type =&gt; blk: {</span> <span class="line" id="L241"> <span class="tok-kw">const</span> register = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader);</span> <span class="line" id="L242"> <span class="tok-kw">const</span> type_offset = <span class="tok-kw">try</span> leb.readULEB128(addr_type, reader);</span> <span class="line" id="L243"> <span class="tok-kw">break</span> :blk .{ .register_type = .{</span> <span class="line" id="L244"> .register = register,</span> <span class="line" id="L245"> .type_offset = type_offset,</span> <span class="line" id="L246"> } };</span> <span class="line" id="L247"> },</span> <span class="line" id="L248"> OP.piece =&gt; .{</span> <span class="line" id="L249"> .composite_location = .{</span> <span class="line" id="L250"> .size = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader),</span> <span class="line" id="L251"> .offset = <span class="tok-number">0</span>,</span> <span class="line" id="L252"> },</span> <span class="line" id="L253"> },</span> <span class="line" id="L254"> OP.bit_piece =&gt; blk: {</span> <span class="line" id="L255"> <span class="tok-kw">const</span> size = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader);</span> <span class="line" id="L256"> <span class="tok-kw">const</span> offset = <span class="tok-kw">try</span> leb.readILEB128(<span class="tok-type">i64</span>, reader);</span> <span class="line" id="L257"> <span class="tok-kw">break</span> :blk .{ .composite_location = .{</span> <span class="line" id="L258"> .size = size,</span> <span class="line" id="L259"> .offset = offset,</span> <span class="line" id="L260"> } };</span> <span class="line" id="L261"> },</span> <span class="line" id="L262"> OP.implicit_value, OP.entry_value =&gt; blk: {</span> <span class="line" id="L263"> <span class="tok-kw">const</span> size = <span class="tok-kw">try</span> leb.readULEB128(<span class="tok-type">u8</span>, reader);</span> <span class="line" id="L264"> <span class="tok-kw">if</span> (stream.pos + size &gt; stream.buffer.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L265"> <span class="tok-kw">const</span> block = stream.buffer[stream.pos..][<span class="tok-number">0</span>..size];</span> <span class="line" id="L266"> stream.pos += size;</span> <span class="line" id="L267"> <span class="tok-kw">break</span> :blk .{</span> <span class="line" id="L268"> .block = block,</span> <span class="line" id="L269"> };</span> <span class="line" id="L270"> },</span> <span class="line" id="L271"> OP.const_type =&gt; blk: {</span> <span class="line" id="L272"> <span class="tok-kw">const</span> type_offset = <span class="tok-kw">try</span> leb.readULEB128(addr_type, reader);</span> <span class="line" id="L273"> <span class="tok-kw">const</span> size = <span class="tok-kw">try</span> reader.readByte();</span> <span class="line" id="L274"> <span class="tok-kw">if</span> (stream.pos + size &gt; stream.buffer.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L275"> <span class="tok-kw">const</span> value_bytes = stream.buffer[stream.pos..][<span class="tok-number">0</span>..size];</span> <span class="line" id="L276"> stream.pos += size;</span> <span class="line" id="L277"> <span class="tok-kw">break</span> :blk .{ .const_type = .{</span> <span class="line" id="L278"> .type_offset = type_offset,</span> <span class="line" id="L279"> .value_bytes = value_bytes,</span> <span class="line" id="L280"> } };</span> <span class="line" id="L281"> },</span> <span class="line" id="L282"> OP.deref_type,</span> <span class="line" id="L283"> OP.xderef_type,</span> <span class="line" id="L284"> =&gt; .{</span> <span class="line" id="L285"> .deref_type = .{</span> <span class="line" id="L286"> .size = <span class="tok-kw">try</span> reader.readByte(),</span> <span class="line" id="L287"> .type_offset = <span class="tok-kw">try</span> leb.readULEB128(addr_type, reader),</span> <span class="line" id="L288"> },</span> <span class="line" id="L289"> },</span> <span class="line" id="L290"> OP.lo_user...OP.hi_user =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedUserOpcode,</span> <span class="line" id="L291"> <span class="tok-kw">else</span> =&gt; <span class="tok-null">null</span>,</span> <span class="line" id="L292"> };</span> <span class="line" id="L293"> }</span> <span class="line" id="L294"></span> <span class="line" id="L295"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">run</span>(</span> <span class="line" id="L296"> self: *Self,</span> <span class="line" id="L297"> expression: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>,</span> <span class="line" id="L298"> allocator: std.mem.Allocator,</span> <span class="line" id="L299"> context: ExpressionContext,</span> <span class="line" id="L300"> initial_value: ?<span class="tok-type">usize</span>,</span> <span class="line" id="L301"> ) ExpressionError!?Value {</span> <span class="line" id="L302"> <span class="tok-kw">if</span> (initial_value) |i| <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = i });</span> <span class="line" id="L303"> <span class="tok-kw">var</span> stream = std.io.fixedBufferStream(expression);</span> <span class="line" id="L304"> <span class="tok-kw">while</span> (<span class="tok-kw">try</span> self.step(&amp;stream, allocator, context)) {}</span> <span class="line" id="L305"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-null">null</span>;</span> <span class="line" id="L306"> <span class="tok-kw">return</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>];</span> <span class="line" id="L307"> }</span> <span class="line" id="L308"></span> <span class="line" id="L309"> <span class="tok-comment">/// Reads an opcode and its operands from `stream`, then executes it</span></span> <span class="line" id="L310"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">step</span>(</span> <span class="line" id="L311"> self: *Self,</span> <span class="line" id="L312"> stream: *std.io.FixedBufferStream([]<span class="tok-kw">const</span> <span class="tok-type">u8</span>),</span> <span class="line" id="L313"> allocator: std.mem.Allocator,</span> <span class="line" id="L314"> context: ExpressionContext,</span> <span class="line" id="L315"> ) ExpressionError!<span class="tok-type">bool</span> {</span> <span class="line" id="L316"> <span class="tok-kw">if</span> (<span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>) != <span class="tok-builtin">@sizeOf</span>(addr_type) <span class="tok-kw">or</span> options.endian != <span class="tok-kw">comptime</span> builtin.target.cpu.arch.endian())</span> <span class="line" id="L317"> <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Execution of non-native address sizes / endianness is not supported&quot;</span>);</span> <span class="line" id="L318"></span> <span class="line" id="L319"> <span class="tok-kw">const</span> opcode = <span class="tok-kw">try</span> stream.reader().readByte();</span> <span class="line" id="L320"> <span class="tok-kw">if</span> (options.call_frame_context <span class="tok-kw">and</span> !isOpcodeValidInCFA(opcode)) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L321"> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L322"></span> <span class="line" id="L323"> <span class="tok-comment">// 2.5.1.1: Literal Encodings</span> </span> <span class="line" id="L324"> OP.lit0...OP.lit31,</span> <span class="line" id="L325"> OP.addr,</span> <span class="line" id="L326"> OP.const1u,</span> <span class="line" id="L327"> OP.const2u,</span> <span class="line" id="L328"> OP.const4u,</span> <span class="line" id="L329"> OP.const8u,</span> <span class="line" id="L330"> OP.const1s,</span> <span class="line" id="L331"> OP.const2s,</span> <span class="line" id="L332"> OP.const4s,</span> <span class="line" id="L333"> OP.const8s,</span> <span class="line" id="L334"> OP.constu,</span> <span class="line" id="L335"> OP.consts,</span> <span class="line" id="L336"> =&gt; <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic }),</span> <span class="line" id="L337"></span> <span class="line" id="L338"> OP.const_type =&gt; {</span> <span class="line" id="L339"> <span class="tok-kw">const</span> const_type = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.const_type;</span> <span class="line" id="L340"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .const_type = .{</span> <span class="line" id="L341"> .type_offset = const_type.type_offset,</span> <span class="line" id="L342"> .value_bytes = const_type.value_bytes,</span> <span class="line" id="L343"> } });</span> <span class="line" id="L344"> },</span> <span class="line" id="L345"></span> <span class="line" id="L346"> OP.addrx,</span> <span class="line" id="L347"> OP.constx,</span> <span class="line" id="L348"> =&gt; {</span> <span class="line" id="L349"> <span class="tok-kw">if</span> (context.compile_unit == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L350"> <span class="tok-kw">if</span> (context.debug_addr == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L351"> <span class="tok-kw">const</span> debug_addr_index = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L352"> <span class="tok-kw">const</span> offset = context.compile_unit.?.addr_base + debug_addr_index;</span> <span class="line" id="L353"> <span class="tok-kw">if</span> (offset &gt;= context.debug_addr.?.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L354"> <span class="tok-kw">const</span> value = mem.readIntSliceNative(<span class="tok-type">usize</span>, context.debug_addr.?[offset..][<span class="tok-number">0</span>..<span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>)]);</span> <span class="line" id="L355"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = value });</span> <span class="line" id="L356"> },</span> <span class="line" id="L357"></span> <span class="line" id="L358"> <span class="tok-comment">// 2.5.1.2: Register Values</span> </span> <span class="line" id="L359"> OP.fbreg =&gt; {</span> <span class="line" id="L360"> <span class="tok-kw">if</span> (context.compile_unit == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L361"> <span class="tok-kw">if</span> (context.compile_unit.?.frame_base == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L362"></span> <span class="line" id="L363"> <span class="tok-kw">const</span> offset: <span class="tok-type">i64</span> = <span class="tok-builtin">@intCast</span>((<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic);</span> <span class="line" id="L364"> _ = offset;</span> <span class="line" id="L365"></span> <span class="line" id="L366"> <span class="tok-kw">switch</span> (context.compile_unit.?.frame_base.?.*) {</span> <span class="line" id="L367"> .ExprLoc =&gt; {</span> <span class="line" id="L368"> <span class="tok-comment">// TODO: Run this expression in a nested stack machine</span> </span> <span class="line" id="L369"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedOpcode;</span> <span class="line" id="L370"> },</span> <span class="line" id="L371"> .LocListOffset =&gt; {</span> <span class="line" id="L372"> <span class="tok-comment">// TODO: Read value from .debug_loclists</span> </span> <span class="line" id="L373"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedOpcode;</span> <span class="line" id="L374"> },</span> <span class="line" id="L375"> .SecOffset =&gt; {</span> <span class="line" id="L376"> <span class="tok-comment">// TODO: Read value from .debug_loclists</span> </span> <span class="line" id="L377"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedOpcode;</span> <span class="line" id="L378"> },</span> <span class="line" id="L379"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidFrameBase,</span> <span class="line" id="L380"> }</span> <span class="line" id="L381"> },</span> <span class="line" id="L382"> OP.breg0...OP.breg31,</span> <span class="line" id="L383"> OP.bregx,</span> <span class="line" id="L384"> =&gt; {</span> <span class="line" id="L385"> <span class="tok-kw">if</span> (context.thread_context == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L386"></span> <span class="line" id="L387"> <span class="tok-kw">const</span> base_register = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.base_register;</span> <span class="line" id="L388"> <span class="tok-kw">var</span> value: <span class="tok-type">i64</span> = <span class="tok-builtin">@intCast</span>(mem.readIntSliceNative(<span class="tok-type">usize</span>, <span class="tok-kw">try</span> abi.regBytes(</span> <span class="line" id="L389"> context.thread_context.?,</span> <span class="line" id="L390"> base_register.base_register,</span> <span class="line" id="L391"> context.reg_context,</span> <span class="line" id="L392"> )));</span> <span class="line" id="L393"> value += base_register.offset;</span> <span class="line" id="L394"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = <span class="tok-builtin">@intCast</span>(value) });</span> <span class="line" id="L395"> },</span> <span class="line" id="L396"> OP.regval_type =&gt; {</span> <span class="line" id="L397"> <span class="tok-kw">const</span> register_type = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.register_type;</span> <span class="line" id="L398"> <span class="tok-kw">const</span> value = mem.readIntSliceNative(<span class="tok-type">usize</span>, <span class="tok-kw">try</span> abi.regBytes(</span> <span class="line" id="L399"> context.thread_context.?,</span> <span class="line" id="L400"> register_type.register,</span> <span class="line" id="L401"> context.reg_context,</span> <span class="line" id="L402"> ));</span> <span class="line" id="L403"> <span class="tok-kw">try</span> self.stack.append(allocator, .{</span> <span class="line" id="L404"> .regval_type = .{</span> <span class="line" id="L405"> .type_offset = register_type.type_offset,</span> <span class="line" id="L406"> .type_size = <span class="tok-builtin">@sizeOf</span>(addr_type),</span> <span class="line" id="L407"> .value = value,</span> <span class="line" id="L408"> },</span> <span class="line" id="L409"> });</span> <span class="line" id="L410"> },</span> <span class="line" id="L411"></span> <span class="line" id="L412"> <span class="tok-comment">// 2.5.1.3: Stack Operations</span> </span> <span class="line" id="L413"> OP.dup =&gt; {</span> <span class="line" id="L414"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L415"> <span class="tok-kw">try</span> self.stack.append(allocator, self.stack.items[self.stack.items.len - <span class="tok-number">1</span>]);</span> <span class="line" id="L416"> },</span> <span class="line" id="L417"> OP.drop =&gt; {</span> <span class="line" id="L418"> _ = self.stack.pop();</span> <span class="line" id="L419"> },</span> <span class="line" id="L420"> OP.pick, OP.over =&gt; {</span> <span class="line" id="L421"> <span class="tok-kw">const</span> stack_index = <span class="tok-kw">if</span> (opcode == OP.over) <span class="tok-number">1</span> <span class="tok-kw">else</span> (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L422"> <span class="tok-kw">if</span> (stack_index &gt;= self.stack.items.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L423"> <span class="tok-kw">try</span> self.stack.append(allocator, self.stack.items[self.stack.items.len - <span class="tok-number">1</span> - stack_index]);</span> <span class="line" id="L424"> },</span> <span class="line" id="L425"> OP.swap =&gt; {</span> <span class="line" id="L426"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L427"> mem.swap(Value, &amp;self.stack.items[self.stack.items.len - <span class="tok-number">1</span>], &amp;self.stack.items[self.stack.items.len - <span class="tok-number">2</span>]);</span> <span class="line" id="L428"> },</span> <span class="line" id="L429"> OP.rot =&gt; {</span> <span class="line" id="L430"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">3</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L431"> <span class="tok-kw">const</span> first = self.stack.items[self.stack.items.len - <span class="tok-number">1</span>];</span> <span class="line" id="L432"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = self.stack.items[self.stack.items.len - <span class="tok-number">2</span>];</span> <span class="line" id="L433"> self.stack.items[self.stack.items.len - <span class="tok-number">2</span>] = self.stack.items[self.stack.items.len - <span class="tok-number">3</span>];</span> <span class="line" id="L434"> self.stack.items[self.stack.items.len - <span class="tok-number">3</span>] = first;</span> <span class="line" id="L435"> },</span> <span class="line" id="L436"> OP.deref,</span> <span class="line" id="L437"> OP.xderef,</span> <span class="line" id="L438"> OP.deref_size,</span> <span class="line" id="L439"> OP.xderef_size,</span> <span class="line" id="L440"> OP.deref_type,</span> <span class="line" id="L441"> OP.xderef_type,</span> <span class="line" id="L442"> =&gt; {</span> <span class="line" id="L443"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L444"> <span class="tok-kw">var</span> addr = <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral();</span> <span class="line" id="L445"> <span class="tok-kw">const</span> addr_space_identifier: ?<span class="tok-type">usize</span> = <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L446"> OP.xderef,</span> <span class="line" id="L447"> OP.xderef_size,</span> <span class="line" id="L448"> OP.xderef_type,</span> <span class="line" id="L449"> =&gt; blk: {</span> <span class="line" id="L450"> _ = self.stack.pop();</span> <span class="line" id="L451"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L452"> <span class="tok-kw">break</span> :blk <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral();</span> <span class="line" id="L453"> },</span> <span class="line" id="L454"> <span class="tok-kw">else</span> =&gt; <span class="tok-null">null</span>,</span> <span class="line" id="L455"> };</span> <span class="line" id="L456"></span> <span class="line" id="L457"> <span class="tok-comment">// Usage of addr_space_identifier in the address calculation is implementation defined.</span> </span> <span class="line" id="L458"> <span class="tok-comment">// This code will need to be updated to handle any architectures that utilize this.</span> </span> <span class="line" id="L459"> _ = addr_space_identifier;</span> <span class="line" id="L460"></span> <span class="line" id="L461"> <span class="tok-kw">if</span> (context.isValidMemory) |isValidMemory| <span class="tok-kw">if</span> (!isValidMemory(addr)) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L462"></span> <span class="line" id="L463"> <span class="tok-kw">const</span> operand = <span class="tok-kw">try</span> readOperand(stream, opcode, context);</span> <span class="line" id="L464"> <span class="tok-kw">const</span> size = <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L465"> OP.deref,</span> <span class="line" id="L466"> OP.xderef,</span> <span class="line" id="L467"> =&gt; <span class="tok-builtin">@sizeOf</span>(addr_type),</span> <span class="line" id="L468"> OP.deref_size,</span> <span class="line" id="L469"> OP.xderef_size,</span> <span class="line" id="L470"> =&gt; operand.?.type_size,</span> <span class="line" id="L471"> OP.deref_type,</span> <span class="line" id="L472"> OP.xderef_type,</span> <span class="line" id="L473"> =&gt; operand.?.deref_type.size,</span> <span class="line" id="L474"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">unreachable</span>,</span> <span class="line" id="L475"> };</span> <span class="line" id="L476"></span> <span class="line" id="L477"> <span class="tok-kw">const</span> value: addr_type = std.math.cast(addr_type, <span class="tok-builtin">@as</span>(<span class="tok-type">u64</span>, <span class="tok-kw">switch</span> (size) {</span> <span class="line" id="L478"> <span class="tok-number">1</span> =&gt; <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u8</span>, <span class="tok-builtin">@ptrFromInt</span>(addr)).*,</span> <span class="line" id="L479"> <span class="tok-number">2</span> =&gt; <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u16</span>, <span class="tok-builtin">@ptrFromInt</span>(addr)).*,</span> <span class="line" id="L480"> <span class="tok-number">4</span> =&gt; <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u32</span>, <span class="tok-builtin">@ptrFromInt</span>(addr)).*,</span> <span class="line" id="L481"> <span class="tok-number">8</span> =&gt; <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u64</span>, <span class="tok-builtin">@ptrFromInt</span>(addr)).*,</span> <span class="line" id="L482"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression,</span> <span class="line" id="L483"> })) <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L484"></span> <span class="line" id="L485"> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L486"> OP.deref_type,</span> <span class="line" id="L487"> OP.xderef_type,</span> <span class="line" id="L488"> =&gt; {</span> <span class="line" id="L489"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L490"> .regval_type = .{</span> <span class="line" id="L491"> .type_offset = operand.?.deref_type.type_offset,</span> <span class="line" id="L492"> .type_size = operand.?.deref_type.size,</span> <span class="line" id="L493"> .value = value,</span> <span class="line" id="L494"> },</span> <span class="line" id="L495"> };</span> <span class="line" id="L496"> },</span> <span class="line" id="L497"> <span class="tok-kw">else</span> =&gt; {</span> <span class="line" id="L498"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{ .generic = value };</span> <span class="line" id="L499"> },</span> <span class="line" id="L500"> }</span> <span class="line" id="L501"> },</span> <span class="line" id="L502"> OP.push_object_address =&gt; {</span> <span class="line" id="L503"> <span class="tok-comment">// In sub-expressions, `push_object_address` is not meaningful (as per the</span> </span> <span class="line" id="L504"> <span class="tok-comment">// spec), so treat it like a nop</span> </span> <span class="line" id="L505"> <span class="tok-kw">if</span> (!context.entry_value_context) {</span> <span class="line" id="L506"> <span class="tok-kw">if</span> (context.object_address == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L507"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = <span class="tok-builtin">@intFromPtr</span>(context.object_address.?) });</span> <span class="line" id="L508"> }</span> <span class="line" id="L509"> },</span> <span class="line" id="L510"> OP.form_tls_address =&gt; {</span> <span class="line" id="L511"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedOpcode;</span> <span class="line" id="L512"> },</span> <span class="line" id="L513"> OP.call_frame_cfa =&gt; {</span> <span class="line" id="L514"> <span class="tok-kw">if</span> (context.cfa) |cfa| {</span> <span class="line" id="L515"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = cfa });</span> <span class="line" id="L516"> } <span class="tok-kw">else</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L517"> },</span> <span class="line" id="L518"></span> <span class="line" id="L519"> <span class="tok-comment">// 2.5.1.4: Arithmetic and Logical Operations</span> </span> <span class="line" id="L520"> OP.abs =&gt; {</span> <span class="line" id="L521"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L522"> <span class="tok-kw">const</span> value: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral());</span> <span class="line" id="L523"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L524"> .generic = std.math.absCast(value),</span> <span class="line" id="L525"> };</span> <span class="line" id="L526"> },</span> <span class="line" id="L527"> OP.@&quot;and&quot; =&gt; {</span> <span class="line" id="L528"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L529"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L530"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L531"> .generic = a &amp; <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(),</span> <span class="line" id="L532"> };</span> <span class="line" id="L533"> },</span> <span class="line" id="L534"> OP.div =&gt; {</span> <span class="line" id="L535"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L536"> <span class="tok-kw">const</span> a: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.pop().asIntegral());</span> <span class="line" id="L537"> <span class="tok-kw">const</span> b: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral());</span> <span class="line" id="L538"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L539"> .generic = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> std.math.divTrunc(<span class="tok-type">isize</span>, b, a)),</span> <span class="line" id="L540"> };</span> <span class="line" id="L541"> },</span> <span class="line" id="L542"> OP.minus =&gt; {</span> <span class="line" id="L543"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L544"> <span class="tok-kw">const</span> b = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L545"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L546"> .generic = <span class="tok-kw">try</span> std.math.sub(addr_type, <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(), b),</span> <span class="line" id="L547"> };</span> <span class="line" id="L548"> },</span> <span class="line" id="L549"> OP.mod =&gt; {</span> <span class="line" id="L550"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L551"> <span class="tok-kw">const</span> a: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.pop().asIntegral());</span> <span class="line" id="L552"> <span class="tok-kw">const</span> b: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral());</span> <span class="line" id="L553"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L554"> .generic = <span class="tok-builtin">@bitCast</span>(<span class="tok-builtin">@mod</span>(b, a)),</span> <span class="line" id="L555"> };</span> <span class="line" id="L556"> },</span> <span class="line" id="L557"> OP.mul =&gt; {</span> <span class="line" id="L558"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L559"> <span class="tok-kw">const</span> a: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.pop().asIntegral());</span> <span class="line" id="L560"> <span class="tok-kw">const</span> b: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral());</span> <span class="line" id="L561"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L562"> .generic = <span class="tok-builtin">@bitCast</span>(<span class="tok-builtin">@mulWithOverflow</span>(a, b)[<span class="tok-number">0</span>]),</span> <span class="line" id="L563"> };</span> <span class="line" id="L564"> },</span> <span class="line" id="L565"> OP.neg =&gt; {</span> <span class="line" id="L566"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L567"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L568"> .generic = <span class="tok-builtin">@bitCast</span>(</span> <span class="line" id="L569"> <span class="tok-kw">try</span> std.math.negate(</span> <span class="line" id="L570"> <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral())),</span> <span class="line" id="L571"> ),</span> <span class="line" id="L572"> ),</span> <span class="line" id="L573"> };</span> <span class="line" id="L574"> },</span> <span class="line" id="L575"> OP.not =&gt; {</span> <span class="line" id="L576"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L577"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L578"> .generic = ~<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(),</span> <span class="line" id="L579"> };</span> <span class="line" id="L580"> },</span> <span class="line" id="L581"> OP.@&quot;or&quot; =&gt; {</span> <span class="line" id="L582"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L583"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L584"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L585"> .generic = a | <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(),</span> <span class="line" id="L586"> };</span> <span class="line" id="L587"> },</span> <span class="line" id="L588"> OP.plus =&gt; {</span> <span class="line" id="L589"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L590"> <span class="tok-kw">const</span> b = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L591"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L592"> .generic = <span class="tok-kw">try</span> std.math.add(addr_type, <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(), b),</span> <span class="line" id="L593"> };</span> <span class="line" id="L594"> },</span> <span class="line" id="L595"> OP.plus_uconst =&gt; {</span> <span class="line" id="L596"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L597"> <span class="tok-kw">const</span> constant = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L598"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L599"> .generic = <span class="tok-kw">try</span> std.math.add(addr_type, <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(), constant),</span> <span class="line" id="L600"> };</span> <span class="line" id="L601"> },</span> <span class="line" id="L602"> OP.shl =&gt; {</span> <span class="line" id="L603"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L604"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L605"> <span class="tok-kw">const</span> b = <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral();</span> <span class="line" id="L606"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L607"> .generic = std.math.shl(<span class="tok-type">usize</span>, b, a),</span> <span class="line" id="L608"> };</span> <span class="line" id="L609"> },</span> <span class="line" id="L610"> OP.shr =&gt; {</span> <span class="line" id="L611"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L612"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L613"> <span class="tok-kw">const</span> b = <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral();</span> <span class="line" id="L614"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L615"> .generic = std.math.shr(<span class="tok-type">usize</span>, b, a),</span> <span class="line" id="L616"> };</span> <span class="line" id="L617"> },</span> <span class="line" id="L618"> OP.shra =&gt; {</span> <span class="line" id="L619"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L620"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L621"> <span class="tok-kw">const</span> b: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(<span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral());</span> <span class="line" id="L622"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L623"> .generic = <span class="tok-builtin">@bitCast</span>(std.math.shr(<span class="tok-type">isize</span>, b, a)),</span> <span class="line" id="L624"> };</span> <span class="line" id="L625"> },</span> <span class="line" id="L626"> OP.xor =&gt; {</span> <span class="line" id="L627"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L628"> <span class="tok-kw">const</span> a = <span class="tok-kw">try</span> self.stack.pop().asIntegral();</span> <span class="line" id="L629"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{</span> <span class="line" id="L630"> .generic = a ^ <span class="tok-kw">try</span> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>].asIntegral(),</span> <span class="line" id="L631"> };</span> <span class="line" id="L632"> },</span> <span class="line" id="L633"></span> <span class="line" id="L634"> <span class="tok-comment">// 2.5.1.5: Control Flow Operations</span> </span> <span class="line" id="L635"> OP.le,</span> <span class="line" id="L636"> OP.ge,</span> <span class="line" id="L637"> OP.eq,</span> <span class="line" id="L638"> OP.lt,</span> <span class="line" id="L639"> OP.gt,</span> <span class="line" id="L640"> OP.ne,</span> <span class="line" id="L641"> =&gt; {</span> <span class="line" id="L642"> <span class="tok-kw">if</span> (self.stack.items.len &lt; <span class="tok-number">2</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L643"> <span class="tok-kw">const</span> a = self.stack.pop();</span> <span class="line" id="L644"> <span class="tok-kw">const</span> b = self.stack.items[self.stack.items.len - <span class="tok-number">1</span>];</span> <span class="line" id="L645"></span> <span class="line" id="L646"> <span class="tok-kw">if</span> (a == .generic <span class="tok-kw">and</span> b == .generic) {</span> <span class="line" id="L647"> <span class="tok-kw">const</span> a_int: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(a.asIntegral() <span class="tok-kw">catch</span> <span class="tok-kw">unreachable</span>);</span> <span class="line" id="L648"> <span class="tok-kw">const</span> b_int: <span class="tok-type">isize</span> = <span class="tok-builtin">@bitCast</span>(b.asIntegral() <span class="tok-kw">catch</span> <span class="tok-kw">unreachable</span>);</span> <span class="line" id="L649"> <span class="tok-kw">const</span> result = <span class="tok-builtin">@intFromBool</span>(<span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L650"> OP.le =&gt; b_int &lt;= a_int,</span> <span class="line" id="L651"> OP.ge =&gt; b_int &gt;= a_int,</span> <span class="line" id="L652"> OP.eq =&gt; b_int == a_int,</span> <span class="line" id="L653"> OP.lt =&gt; b_int &lt; a_int,</span> <span class="line" id="L654"> OP.gt =&gt; b_int &gt; a_int,</span> <span class="line" id="L655"> OP.ne =&gt; b_int != a_int,</span> <span class="line" id="L656"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">unreachable</span>,</span> <span class="line" id="L657"> });</span> <span class="line" id="L658"></span> <span class="line" id="L659"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{ .generic = result };</span> <span class="line" id="L660"> } <span class="tok-kw">else</span> {</span> <span class="line" id="L661"> <span class="tok-comment">// TODO: Load the types referenced by these values, find their comparison operator, and run it</span> </span> <span class="line" id="L662"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedTypedComparison;</span> <span class="line" id="L663"> }</span> <span class="line" id="L664"> },</span> <span class="line" id="L665"> OP.skip, OP.bra =&gt; {</span> <span class="line" id="L666"> <span class="tok-kw">const</span> branch_offset = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.branch_offset;</span> <span class="line" id="L667"> <span class="tok-kw">const</span> condition = <span class="tok-kw">if</span> (opcode == OP.bra) blk: {</span> <span class="line" id="L668"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L669"> <span class="tok-kw">break</span> :blk <span class="tok-kw">try</span> self.stack.pop().asIntegral() != <span class="tok-number">0</span>;</span> <span class="line" id="L670"> } <span class="tok-kw">else</span> <span class="tok-null">true</span>;</span> <span class="line" id="L671"></span> <span class="line" id="L672"> <span class="tok-kw">if</span> (condition) {</span> <span class="line" id="L673"> <span class="tok-kw">const</span> new_pos = std.math.cast(</span> <span class="line" id="L674"> <span class="tok-type">usize</span>,</span> <span class="line" id="L675"> <span class="tok-kw">try</span> std.math.add(<span class="tok-type">isize</span>, <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@intCast</span>(stream.pos)), branch_offset),</span> <span class="line" id="L676"> ) <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L677"></span> <span class="line" id="L678"> <span class="tok-kw">if</span> (new_pos &lt; <span class="tok-number">0</span> <span class="tok-kw">or</span> new_pos &gt; stream.buffer.len) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L679"> stream.pos = new_pos;</span> <span class="line" id="L680"> }</span> <span class="line" id="L681"> },</span> <span class="line" id="L682"> OP.call2,</span> <span class="line" id="L683"> OP.call4,</span> <span class="line" id="L684"> OP.call_ref,</span> <span class="line" id="L685"> =&gt; {</span> <span class="line" id="L686"> <span class="tok-kw">const</span> debug_info_offset = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L687"> _ = debug_info_offset;</span> <span class="line" id="L688"></span> <span class="line" id="L689"> <span class="tok-comment">// TODO: Load a DIE entry at debug_info_offset in a .debug_info section (the spec says that it</span> </span> <span class="line" id="L690"> <span class="tok-comment">// can be in a separate exe / shared object from the one containing this expression).</span> </span> <span class="line" id="L691"> <span class="tok-comment">// Transfer control to the DW_AT_location attribute, with the current stack as input.</span> </span> <span class="line" id="L692"></span> <span class="line" id="L693"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedExpressionCall;</span> <span class="line" id="L694"> },</span> <span class="line" id="L695"></span> <span class="line" id="L696"> <span class="tok-comment">// 2.5.1.6: Type Conversions</span> </span> <span class="line" id="L697"> OP.convert =&gt; {</span> <span class="line" id="L698"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L699"> <span class="tok-kw">const</span> type_offset = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L700"></span> <span class="line" id="L701"> <span class="tok-comment">// TODO: Load the DW_TAG_base_type entries in context.compile_unit and verify both types are the same size</span> </span> <span class="line" id="L702"> <span class="tok-kw">const</span> value = self.stack.items[self.stack.items.len - <span class="tok-number">1</span>];</span> <span class="line" id="L703"> <span class="tok-kw">if</span> (type_offset == <span class="tok-number">0</span>) {</span> <span class="line" id="L704"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{ .generic = <span class="tok-kw">try</span> value.asIntegral() };</span> <span class="line" id="L705"> } <span class="tok-kw">else</span> {</span> <span class="line" id="L706"> <span class="tok-comment">// TODO: Load the DW_TAG_base_type entry in context.compile_unit, find a conversion operator</span> </span> <span class="line" id="L707"> <span class="tok-comment">// from the old type to the new type, run it.</span> </span> <span class="line" id="L708"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnimplementedTypeConversion;</span> <span class="line" id="L709"> }</span> <span class="line" id="L710"> },</span> <span class="line" id="L711"> OP.reinterpret =&gt; {</span> <span class="line" id="L712"> <span class="tok-kw">if</span> (self.stack.items.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidExpression;</span> <span class="line" id="L713"> <span class="tok-kw">const</span> type_offset = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.generic;</span> <span class="line" id="L714"></span> <span class="line" id="L715"> <span class="tok-comment">// TODO: Load the DW_TAG_base_type entries in context.compile_unit and verify both types are the same size</span> </span> <span class="line" id="L716"> <span class="tok-kw">const</span> value = self.stack.items[self.stack.items.len - <span class="tok-number">1</span>];</span> <span class="line" id="L717"> <span class="tok-kw">if</span> (type_offset == <span class="tok-number">0</span>) {</span> <span class="line" id="L718"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = .{ .generic = <span class="tok-kw">try</span> value.asIntegral() };</span> <span class="line" id="L719"> } <span class="tok-kw">else</span> {</span> <span class="line" id="L720"> self.stack.items[self.stack.items.len - <span class="tok-number">1</span>] = <span class="tok-kw">switch</span> (value) {</span> <span class="line" id="L721"> .generic =&gt; |v| .{</span> <span class="line" id="L722"> .regval_type = .{</span> <span class="line" id="L723"> .type_offset = type_offset,</span> <span class="line" id="L724"> .type_size = <span class="tok-builtin">@sizeOf</span>(addr_type),</span> <span class="line" id="L725"> .value = v,</span> <span class="line" id="L726"> },</span> <span class="line" id="L727"> },</span> <span class="line" id="L728"> .regval_type =&gt; |r| .{</span> <span class="line" id="L729"> .regval_type = .{</span> <span class="line" id="L730"> .type_offset = type_offset,</span> <span class="line" id="L731"> .type_size = r.type_size,</span> <span class="line" id="L732"> .value = r.value,</span> <span class="line" id="L733"> },</span> <span class="line" id="L734"> },</span> <span class="line" id="L735"> .const_type =&gt; |c| .{</span> <span class="line" id="L736"> .const_type = .{</span> <span class="line" id="L737"> .type_offset = type_offset,</span> <span class="line" id="L738"> .value_bytes = c.value_bytes,</span> <span class="line" id="L739"> },</span> <span class="line" id="L740"> },</span> <span class="line" id="L741"> };</span> <span class="line" id="L742"> }</span> <span class="line" id="L743"> },</span> <span class="line" id="L744"></span> <span class="line" id="L745"> <span class="tok-comment">// 2.5.1.7: Special Operations</span> </span> <span class="line" id="L746"> OP.nop =&gt; {},</span> <span class="line" id="L747"> OP.entry_value =&gt; {</span> <span class="line" id="L748"> <span class="tok-kw">const</span> block = (<span class="tok-kw">try</span> readOperand(stream, opcode, context)).?.block;</span> <span class="line" id="L749"> <span class="tok-kw">if</span> (block.len == <span class="tok-number">0</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidSubExpression;</span> <span class="line" id="L750"></span> <span class="line" id="L751"> <span class="tok-comment">// TODO: The spec states that this sub-expression needs to observe the state (ie. registers)</span> </span> <span class="line" id="L752"> <span class="tok-comment">// as it was upon entering the current subprogram. If this isn't being called at the</span> </span> <span class="line" id="L753"> <span class="tok-comment">// end of a frame unwind operation, an additional ThreadContext with this state will be needed.</span> </span> <span class="line" id="L754"></span> <span class="line" id="L755"> <span class="tok-kw">if</span> (isOpcodeRegisterLocation(block[<span class="tok-number">0</span>])) {</span> <span class="line" id="L756"> <span class="tok-kw">if</span> (context.thread_context == <span class="tok-null">null</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.IncompleteExpressionContext;</span> <span class="line" id="L757"></span> <span class="line" id="L758"> <span class="tok-kw">var</span> block_stream = std.io.fixedBufferStream(block);</span> <span class="line" id="L759"> <span class="tok-kw">const</span> register = (<span class="tok-kw">try</span> readOperand(&amp;block_stream, block[<span class="tok-number">0</span>], context)).?.register;</span> <span class="line" id="L760"> <span class="tok-kw">const</span> value = mem.readIntSliceNative(<span class="tok-type">usize</span>, <span class="tok-kw">try</span> abi.regBytes(context.thread_context.?, register, context.reg_context));</span> <span class="line" id="L761"> <span class="tok-kw">try</span> self.stack.append(allocator, .{ .generic = value });</span> <span class="line" id="L762"> } <span class="tok-kw">else</span> {</span> <span class="line" id="L763"> <span class="tok-kw">var</span> stack_machine: Self = .{};</span> <span class="line" id="L764"> <span class="tok-kw">defer</span> stack_machine.deinit(allocator);</span> <span class="line" id="L765"></span> <span class="line" id="L766"> <span class="tok-kw">var</span> sub_context = context;</span> <span class="line" id="L767"> sub_context.entry_value_context = <span class="tok-null">true</span>;</span> <span class="line" id="L768"> <span class="tok-kw">const</span> result = <span class="tok-kw">try</span> stack_machine.run(block, allocator, sub_context, <span class="tok-null">null</span>);</span> <span class="line" id="L769"> <span class="tok-kw">try</span> self.stack.append(allocator, result <span class="tok-kw">orelse</span> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidSubExpression);</span> <span class="line" id="L770"> }</span> <span class="line" id="L771"> },</span> <span class="line" id="L772"></span> <span class="line" id="L773"> <span class="tok-comment">// These have already been handled by readOperand</span> </span> <span class="line" id="L774"> OP.lo_user...OP.hi_user =&gt; <span class="tok-kw">unreachable</span>,</span> <span class="line" id="L775"> <span class="tok-kw">else</span> =&gt; {</span> <span class="line" id="L776"> <span class="tok-comment">//std.debug.print(&quot;Unknown DWARF expression opcode: {x}\n&quot;, .{opcode});</span> </span> <span class="line" id="L777"> <span class="tok-kw">return</span> <span class="tok-kw">error</span>.UnknownExpressionOpcode;</span> <span class="line" id="L778"> },</span> <span class="line" id="L779"> }</span> <span class="line" id="L780"></span> <span class="line" id="L781"> <span class="tok-kw">return</span> stream.pos &lt; stream.buffer.len;</span> <span class="line" id="L782"> }</span> <span class="line" id="L783"> };</span> <span class="line" id="L784">}</span> <span class="line" id="L785"></span> <span class="line" id="L786"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">Builder</span>(<span class="tok-kw">comptime</span> options: ExpressionOptions) <span class="tok-type">type</span> {</span> <span class="line" id="L787"> <span class="tok-kw">const</span> addr_type = <span class="tok-kw">switch</span> (options.addr_size) {</span> <span class="line" id="L788"> <span class="tok-number">2</span> =&gt; <span class="tok-type">u16</span>,</span> <span class="line" id="L789"> <span class="tok-number">4</span> =&gt; <span class="tok-type">u32</span>,</span> <span class="line" id="L790"> <span class="tok-number">8</span> =&gt; <span class="tok-type">u64</span>,</span> <span class="line" id="L791"> <span class="tok-kw">else</span> =&gt; <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Unsupported address size of &quot;</span> ++ options.addr_size),</span> <span class="line" id="L792"> };</span> <span class="line" id="L793"></span> <span class="line" id="L794"> <span class="tok-kw">return</span> <span class="tok-kw">struct</span> {</span> <span class="line" id="L795"> <span class="tok-comment">/// Zero-operand instructions</span></span> <span class="line" id="L796"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeOpcode</span>(writer: <span class="tok-kw">anytype</span>, <span class="tok-kw">comptime</span> opcode: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L797"> <span class="tok-kw">if</span> (options.call_frame_context <span class="tok-kw">and</span> !<span class="tok-kw">comptime</span> isOpcodeValidInCFA(opcode)) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L798"> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L799"> OP.dup,</span> <span class="line" id="L800"> OP.drop,</span> <span class="line" id="L801"> OP.over,</span> <span class="line" id="L802"> OP.swap,</span> <span class="line" id="L803"> OP.rot,</span> <span class="line" id="L804"> OP.deref,</span> <span class="line" id="L805"> OP.xderef,</span> <span class="line" id="L806"> OP.push_object_address,</span> <span class="line" id="L807"> OP.form_tls_address,</span> <span class="line" id="L808"> OP.call_frame_cfa,</span> <span class="line" id="L809"> OP.abs,</span> <span class="line" id="L810"> OP.@&quot;and&quot;,</span> <span class="line" id="L811"> OP.div,</span> <span class="line" id="L812"> OP.minus,</span> <span class="line" id="L813"> OP.mod,</span> <span class="line" id="L814"> OP.mul,</span> <span class="line" id="L815"> OP.neg,</span> <span class="line" id="L816"> OP.not,</span> <span class="line" id="L817"> OP.@&quot;or&quot;,</span> <span class="line" id="L818"> OP.plus,</span> <span class="line" id="L819"> OP.shl,</span> <span class="line" id="L820"> OP.shr,</span> <span class="line" id="L821"> OP.shra,</span> <span class="line" id="L822"> OP.xor,</span> <span class="line" id="L823"> OP.le,</span> <span class="line" id="L824"> OP.ge,</span> <span class="line" id="L825"> OP.eq,</span> <span class="line" id="L826"> OP.lt,</span> <span class="line" id="L827"> OP.gt,</span> <span class="line" id="L828"> OP.ne,</span> <span class="line" id="L829"> OP.nop,</span> <span class="line" id="L830"> OP.stack_value,</span> <span class="line" id="L831"> =&gt; <span class="tok-kw">try</span> writer.writeByte(opcode),</span> <span class="line" id="L832"> <span class="tok-kw">else</span> =&gt; <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;This opcode requires operands, use `write&lt;Opcode&gt;()` instead&quot;</span>),</span> <span class="line" id="L833"> }</span> <span class="line" id="L834"> }</span> <span class="line" id="L835"></span> <span class="line" id="L836"> <span class="tok-comment">// 2.5.1.1: Literal Encodings</span> </span> <span class="line" id="L837"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeLiteral</span>(writer: <span class="tok-kw">anytype</span>, literal: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L838"> <span class="tok-kw">switch</span> (literal) {</span> <span class="line" id="L839"> <span class="tok-number">0</span>...<span class="tok-number">31</span> =&gt; |n| <span class="tok-kw">try</span> writer.writeByte(n + OP.lit0),</span> <span class="line" id="L840"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidLiteral,</span> <span class="line" id="L841"> }</span> <span class="line" id="L842"> }</span> <span class="line" id="L843"></span> <span class="line" id="L844"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeConst</span>(writer: <span class="tok-kw">anytype</span>, <span class="tok-kw">comptime</span> T: <span class="tok-type">type</span>, value: T) !<span class="tok-type">void</span> {</span> <span class="line" id="L845"> <span class="tok-kw">if</span> (<span class="tok-builtin">@typeInfo</span>(T) != .Int) <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Constants must be integers&quot;</span>);</span> <span class="line" id="L846"></span> <span class="line" id="L847"> <span class="tok-kw">switch</span> (T) {</span> <span class="line" id="L848"> <span class="tok-type">u8</span>, <span class="tok-type">i8</span>, <span class="tok-type">u16</span>, <span class="tok-type">i16</span>, <span class="tok-type">u32</span>, <span class="tok-type">i32</span>, <span class="tok-type">u64</span>, <span class="tok-type">i64</span> =&gt; {</span> <span class="line" id="L849"> <span class="tok-kw">try</span> writer.writeByte(<span class="tok-kw">switch</span> (T) {</span> <span class="line" id="L850"> <span class="tok-type">u8</span> =&gt; OP.const1u,</span> <span class="line" id="L851"> <span class="tok-type">i8</span> =&gt; OP.const1s,</span> <span class="line" id="L852"> <span class="tok-type">u16</span> =&gt; OP.const2u,</span> <span class="line" id="L853"> <span class="tok-type">i16</span> =&gt; OP.const2s,</span> <span class="line" id="L854"> <span class="tok-type">u32</span> =&gt; OP.const4u,</span> <span class="line" id="L855"> <span class="tok-type">i32</span> =&gt; OP.const4s,</span> <span class="line" id="L856"> <span class="tok-type">u64</span> =&gt; OP.const8u,</span> <span class="line" id="L857"> <span class="tok-type">i64</span> =&gt; OP.const8s,</span> <span class="line" id="L858"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">unreachable</span>,</span> <span class="line" id="L859"> });</span> <span class="line" id="L860"></span> <span class="line" id="L861"> <span class="tok-kw">try</span> writer.writeInt(T, value, options.endian);</span> <span class="line" id="L862"> },</span> <span class="line" id="L863"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">switch</span> (<span class="tok-builtin">@typeInfo</span>(T).Int.signedness) {</span> <span class="line" id="L864"> .unsigned =&gt; {</span> <span class="line" id="L865"> <span class="tok-kw">try</span> writer.writeByte(OP.constu);</span> <span class="line" id="L866"> <span class="tok-kw">try</span> leb.writeULEB128(writer, value);</span> <span class="line" id="L867"> },</span> <span class="line" id="L868"> .signed =&gt; {</span> <span class="line" id="L869"> <span class="tok-kw">try</span> writer.writeByte(OP.consts);</span> <span class="line" id="L870"> <span class="tok-kw">try</span> leb.writeILEB128(writer, value);</span> <span class="line" id="L871"> },</span> <span class="line" id="L872"> },</span> <span class="line" id="L873"> }</span> <span class="line" id="L874"> }</span> <span class="line" id="L875"></span> <span class="line" id="L876"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeConstx</span>(writer: <span class="tok-kw">anytype</span>, debug_addr_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L877"> <span class="tok-kw">try</span> writer.writeByte(OP.constx);</span> <span class="line" id="L878"> <span class="tok-kw">try</span> leb.writeULEB128(writer, debug_addr_offset);</span> <span class="line" id="L879"> }</span> <span class="line" id="L880"></span> <span class="line" id="L881"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeConstType</span>(writer: <span class="tok-kw">anytype</span>, die_offset: <span class="tok-kw">anytype</span>, value_bytes: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L882"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L883"> <span class="tok-kw">if</span> (value_bytes.len &gt; <span class="tok-number">0xff</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidTypeLength;</span> <span class="line" id="L884"> <span class="tok-kw">try</span> writer.writeByte(OP.const_type);</span> <span class="line" id="L885"> <span class="tok-kw">try</span> leb.writeULEB128(writer, die_offset);</span> <span class="line" id="L886"> <span class="tok-kw">try</span> writer.writeByte(<span class="tok-builtin">@intCast</span>(value_bytes.len));</span> <span class="line" id="L887"> <span class="tok-kw">try</span> writer.writeAll(value_bytes);</span> <span class="line" id="L888"> }</span> <span class="line" id="L889"></span> <span class="line" id="L890"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeAddr</span>(writer: <span class="tok-kw">anytype</span>, value: addr_type) !<span class="tok-type">void</span> {</span> <span class="line" id="L891"> <span class="tok-kw">try</span> writer.writeByte(OP.addr);</span> <span class="line" id="L892"> <span class="tok-kw">try</span> writer.writeInt(addr_type, value, options.endian);</span> <span class="line" id="L893"> }</span> <span class="line" id="L894"></span> <span class="line" id="L895"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeAddrx</span>(writer: <span class="tok-kw">anytype</span>, debug_addr_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L896"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L897"> <span class="tok-kw">try</span> writer.writeByte(OP.addrx);</span> <span class="line" id="L898"> <span class="tok-kw">try</span> leb.writeULEB128(writer, debug_addr_offset);</span> <span class="line" id="L899"> }</span> <span class="line" id="L900"></span> <span class="line" id="L901"> <span class="tok-comment">// 2.5.1.2: Register Values</span> </span> <span class="line" id="L902"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeFbreg</span>(writer: <span class="tok-kw">anytype</span>, offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L903"> <span class="tok-kw">try</span> writer.writeByte(OP.fbreg);</span> <span class="line" id="L904"> <span class="tok-kw">try</span> leb.writeILEB128(writer, offset);</span> <span class="line" id="L905"> }</span> <span class="line" id="L906"></span> <span class="line" id="L907"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeBreg</span>(writer: <span class="tok-kw">anytype</span>, register: <span class="tok-type">u8</span>, offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L908"> <span class="tok-kw">if</span> (register &gt; <span class="tok-number">31</span>) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidRegister;</span> <span class="line" id="L909"> <span class="tok-kw">try</span> writer.writeByte(OP.breg0 + register);</span> <span class="line" id="L910"> <span class="tok-kw">try</span> leb.writeILEB128(writer, offset);</span> <span class="line" id="L911"> }</span> <span class="line" id="L912"></span> <span class="line" id="L913"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeBregx</span>(writer: <span class="tok-kw">anytype</span>, register: <span class="tok-kw">anytype</span>, offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L914"> <span class="tok-kw">try</span> writer.writeByte(OP.bregx);</span> <span class="line" id="L915"> <span class="tok-kw">try</span> leb.writeULEB128(writer, register);</span> <span class="line" id="L916"> <span class="tok-kw">try</span> leb.writeILEB128(writer, offset);</span> <span class="line" id="L917"> }</span> <span class="line" id="L918"></span> <span class="line" id="L919"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeRegvalType</span>(writer: <span class="tok-kw">anytype</span>, register: <span class="tok-kw">anytype</span>, offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L920"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L921"> <span class="tok-kw">try</span> writer.writeByte(OP.regval_type);</span> <span class="line" id="L922"> <span class="tok-kw">try</span> leb.writeULEB128(writer, register);</span> <span class="line" id="L923"> <span class="tok-kw">try</span> leb.writeULEB128(writer, offset);</span> <span class="line" id="L924"> }</span> <span class="line" id="L925"></span> <span class="line" id="L926"> <span class="tok-comment">// 2.5.1.3: Stack Operations</span> </span> <span class="line" id="L927"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writePick</span>(writer: <span class="tok-kw">anytype</span>, index: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L928"> <span class="tok-kw">try</span> writer.writeByte(OP.pick);</span> <span class="line" id="L929"> <span class="tok-kw">try</span> writer.writeByte(index);</span> <span class="line" id="L930"> }</span> <span class="line" id="L931"></span> <span class="line" id="L932"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeDerefSize</span>(writer: <span class="tok-kw">anytype</span>, size: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L933"> <span class="tok-kw">try</span> writer.writeByte(OP.deref_size);</span> <span class="line" id="L934"> <span class="tok-kw">try</span> writer.writeByte(size);</span> <span class="line" id="L935"> }</span> <span class="line" id="L936"></span> <span class="line" id="L937"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeXDerefSize</span>(writer: <span class="tok-kw">anytype</span>, size: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L938"> <span class="tok-kw">try</span> writer.writeByte(OP.xderef_size);</span> <span class="line" id="L939"> <span class="tok-kw">try</span> writer.writeByte(size);</span> <span class="line" id="L940"> }</span> <span class="line" id="L941"></span> <span class="line" id="L942"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeDerefType</span>(writer: <span class="tok-kw">anytype</span>, size: <span class="tok-type">u8</span>, die_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L943"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L944"> <span class="tok-kw">try</span> writer.writeByte(OP.deref_type);</span> <span class="line" id="L945"> <span class="tok-kw">try</span> writer.writeByte(size);</span> <span class="line" id="L946"> <span class="tok-kw">try</span> leb.writeULEB128(writer, die_offset);</span> <span class="line" id="L947"> }</span> <span class="line" id="L948"></span> <span class="line" id="L949"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeXDerefType</span>(writer: <span class="tok-kw">anytype</span>, size: <span class="tok-type">u8</span>, die_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L950"> <span class="tok-kw">try</span> writer.writeByte(OP.xderef_type);</span> <span class="line" id="L951"> <span class="tok-kw">try</span> writer.writeByte(size);</span> <span class="line" id="L952"> <span class="tok-kw">try</span> leb.writeULEB128(writer, die_offset);</span> <span class="line" id="L953"> }</span> <span class="line" id="L954"></span> <span class="line" id="L955"> <span class="tok-comment">// 2.5.1.4: Arithmetic and Logical Operations</span> </span> <span class="line" id="L956"></span> <span class="line" id="L957"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writePlusUconst</span>(writer: <span class="tok-kw">anytype</span>, uint_value: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L958"> <span class="tok-kw">try</span> writer.writeByte(OP.plus_uconst);</span> <span class="line" id="L959"> <span class="tok-kw">try</span> leb.writeULEB128(writer, uint_value);</span> <span class="line" id="L960"> }</span> <span class="line" id="L961"></span> <span class="line" id="L962"> <span class="tok-comment">// 2.5.1.5: Control Flow Operations</span> </span> <span class="line" id="L963"></span> <span class="line" id="L964"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeSkip</span>(writer: <span class="tok-kw">anytype</span>, offset: <span class="tok-type">i16</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L965"> <span class="tok-kw">try</span> writer.writeByte(OP.skip);</span> <span class="line" id="L966"> <span class="tok-kw">try</span> writer.writeInt(<span class="tok-type">i16</span>, offset, options.endian);</span> <span class="line" id="L967"> }</span> <span class="line" id="L968"></span> <span class="line" id="L969"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeBra</span>(writer: <span class="tok-kw">anytype</span>, offset: <span class="tok-type">i16</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L970"> <span class="tok-kw">try</span> writer.writeByte(OP.bra);</span> <span class="line" id="L971"> <span class="tok-kw">try</span> writer.writeInt(<span class="tok-type">i16</span>, offset, options.endian);</span> <span class="line" id="L972"> }</span> <span class="line" id="L973"></span> <span class="line" id="L974"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeCall</span>(writer: <span class="tok-kw">anytype</span>, <span class="tok-kw">comptime</span> T: <span class="tok-type">type</span>, offset: T) !<span class="tok-type">void</span> {</span> <span class="line" id="L975"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L976"> <span class="tok-kw">switch</span> (T) {</span> <span class="line" id="L977"> <span class="tok-type">u16</span> =&gt; <span class="tok-kw">try</span> writer.writeByte(OP.call2),</span> <span class="line" id="L978"> <span class="tok-type">u32</span> =&gt; <span class="tok-kw">try</span> writer.writeByte(OP.call4),</span> <span class="line" id="L979"> <span class="tok-kw">else</span> =&gt; <span class="tok-builtin">@compileError</span>(<span class="tok-str">&quot;Call operand must be a 2 or 4 byte offset&quot;</span>),</span> <span class="line" id="L980"> }</span> <span class="line" id="L981"></span> <span class="line" id="L982"> <span class="tok-kw">try</span> writer.writeInt(T, offset, options.endian);</span> <span class="line" id="L983"> }</span> <span class="line" id="L984"></span> <span class="line" id="L985"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeCallRef</span>(writer: <span class="tok-kw">anytype</span>, <span class="tok-kw">comptime</span> is_64: <span class="tok-type">bool</span>, value: <span class="tok-kw">if</span> (is_64) <span class="tok-type">u64</span> <span class="tok-kw">else</span> <span class="tok-type">u32</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L986"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L987"> <span class="tok-kw">try</span> writer.writeByte(OP.call_ref);</span> <span class="line" id="L988"> <span class="tok-kw">try</span> writer.writeInt(<span class="tok-kw">if</span> (is_64) <span class="tok-type">u64</span> <span class="tok-kw">else</span> <span class="tok-type">u32</span>, value, options.endian);</span> <span class="line" id="L989"> }</span> <span class="line" id="L990"></span> <span class="line" id="L991"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeConvert</span>(writer: <span class="tok-kw">anytype</span>, die_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L992"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L993"> <span class="tok-kw">try</span> writer.writeByte(OP.convert);</span> <span class="line" id="L994"> <span class="tok-kw">try</span> leb.writeULEB128(writer, die_offset);</span> <span class="line" id="L995"> }</span> <span class="line" id="L996"></span> <span class="line" id="L997"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeReinterpret</span>(writer: <span class="tok-kw">anytype</span>, die_offset: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L998"> <span class="tok-kw">if</span> (options.call_frame_context) <span class="tok-kw">return</span> <span class="tok-kw">error</span>.InvalidCFAOpcode;</span> <span class="line" id="L999"> <span class="tok-kw">try</span> writer.writeByte(OP.reinterpret);</span> <span class="line" id="L1000"> <span class="tok-kw">try</span> leb.writeULEB128(writer, die_offset);</span> <span class="line" id="L1001"> }</span> <span class="line" id="L1002"></span> <span class="line" id="L1003"> <span class="tok-comment">// 2.5.1.7: Special Operations</span> </span> <span class="line" id="L1004"></span> <span class="line" id="L1005"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeEntryValue</span>(writer: <span class="tok-kw">anytype</span>, expression: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L1006"> <span class="tok-kw">try</span> writer.writeByte(OP.entry_value);</span> <span class="line" id="L1007"> <span class="tok-kw">try</span> leb.writeULEB128(writer, expression.len);</span> <span class="line" id="L1008"> <span class="tok-kw">try</span> writer.writeAll(expression);</span> <span class="line" id="L1009"> }</span> <span class="line" id="L1010"></span> <span class="line" id="L1011"> <span class="tok-comment">// 2.6: Location Descriptions</span> </span> <span class="line" id="L1012"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeReg</span>(writer: <span class="tok-kw">anytype</span>, register: <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L1013"> <span class="tok-kw">try</span> writer.writeByte(OP.reg0 + register);</span> <span class="line" id="L1014"> }</span> <span class="line" id="L1015"></span> <span class="line" id="L1016"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeRegx</span>(writer: <span class="tok-kw">anytype</span>, register: <span class="tok-kw">anytype</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L1017"> <span class="tok-kw">try</span> writer.writeByte(OP.regx);</span> <span class="line" id="L1018"> <span class="tok-kw">try</span> leb.writeULEB128(writer, register);</span> <span class="line" id="L1019"> }</span> <span class="line" id="L1020"></span> <span class="line" id="L1021"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">writeImplicitValue</span>(writer: <span class="tok-kw">anytype</span>, value_bytes: []<span class="tok-kw">const</span> <span class="tok-type">u8</span>) !<span class="tok-type">void</span> {</span> <span class="line" id="L1022"> <span class="tok-kw">try</span> writer.writeByte(OP.implicit_value);</span> <span class="line" id="L1023"> <span class="tok-kw">try</span> leb.writeULEB128(writer, value_bytes.len);</span> <span class="line" id="L1024"> <span class="tok-kw">try</span> writer.writeAll(value_bytes);</span> <span class="line" id="L1025"> }</span> <span class="line" id="L1026"> };</span> <span class="line" id="L1027">}</span> <span class="line" id="L1028"></span> <span class="line" id="L1029"><span class="tok-comment">// Certain opcodes are not allowed in a CFA context, see 6.4.2</span> </span> <span class="line" id="L1030"><span class="tok-kw">fn</span> <span class="tok-fn">isOpcodeValidInCFA</span>(opcode: <span class="tok-type">u8</span>) <span class="tok-type">bool</span> {</span> <span class="line" id="L1031"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L1032"> OP.addrx,</span> <span class="line" id="L1033"> OP.call2,</span> <span class="line" id="L1034"> OP.call4,</span> <span class="line" id="L1035"> OP.call_ref,</span> <span class="line" id="L1036"> OP.const_type,</span> <span class="line" id="L1037"> OP.constx,</span> <span class="line" id="L1038"> OP.convert,</span> <span class="line" id="L1039"> OP.deref_type,</span> <span class="line" id="L1040"> OP.regval_type,</span> <span class="line" id="L1041"> OP.reinterpret,</span> <span class="line" id="L1042"> OP.push_object_address,</span> <span class="line" id="L1043"> OP.call_frame_cfa,</span> <span class="line" id="L1044"> =&gt; <span class="tok-null">false</span>,</span> <span class="line" id="L1045"> <span class="tok-kw">else</span> =&gt; <span class="tok-null">true</span>,</span> <span class="line" id="L1046"> };</span> <span class="line" id="L1047">}</span> <span class="line" id="L1048"></span> <span class="line" id="L1049"><span class="tok-kw">fn</span> <span class="tok-fn">isOpcodeRegisterLocation</span>(opcode: <span class="tok-type">u8</span>) <span class="tok-type">bool</span> {</span> <span class="line" id="L1050"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (opcode) {</span> <span class="line" id="L1051"> OP.reg0...OP.reg31, OP.regx =&gt; <span class="tok-null">true</span>,</span> <span class="line" id="L1052"> <span class="tok-kw">else</span> =&gt; <span class="tok-null">false</span>,</span> <span class="line" id="L1053"> };</span> <span class="line" id="L1054">}</span> <span class="line" id="L1055"></span> <span class="line" id="L1056"><span class="tok-kw">const</span> testing = std.testing;</span> <span class="line" id="L1057"><span class="tok-kw">test</span> <span class="tok-str">&quot;DWARF expressions&quot;</span> {</span> <span class="line" id="L1058"> <span class="tok-kw">const</span> allocator = std.testing.allocator;</span> <span class="line" id="L1059"></span> <span class="line" id="L1060"> <span class="tok-kw">const</span> options = ExpressionOptions{};</span> <span class="line" id="L1061"> <span class="tok-kw">var</span> stack_machine = StackMachine(options){};</span> <span class="line" id="L1062"> <span class="tok-kw">defer</span> stack_machine.deinit(allocator);</span> <span class="line" id="L1063"></span> <span class="line" id="L1064"> <span class="tok-kw">const</span> b = Builder(options);</span> <span class="line" id="L1065"></span> <span class="line" id="L1066"> <span class="tok-kw">var</span> program = std.ArrayList(<span class="tok-type">u8</span>).init(allocator);</span> <span class="line" id="L1067"> <span class="tok-kw">defer</span> program.deinit();</span> <span class="line" id="L1068"></span> <span class="line" id="L1069"> <span class="tok-kw">const</span> writer = program.writer();</span> <span class="line" id="L1070"></span> <span class="line" id="L1071"> <span class="tok-comment">// Literals</span> </span> <span class="line" id="L1072"> {</span> <span class="line" id="L1073"> <span class="tok-kw">const</span> context = ExpressionContext{};</span> <span class="line" id="L1074"> <span class="tok-kw">for</span> (<span class="tok-number">0</span>..<span class="tok-number">32</span>) |i| {</span> <span class="line" id="L1075"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-builtin">@intCast</span>(i));</span> <span class="line" id="L1076"> }</span> <span class="line" id="L1077"></span> <span class="line" id="L1078"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-number">0</span>);</span> <span class="line" id="L1079"></span> <span class="line" id="L1080"> <span class="tok-kw">for</span> (<span class="tok-number">0</span>..<span class="tok-number">32</span>) |i| {</span> <span class="line" id="L1081"> <span class="tok-kw">const</span> expected = <span class="tok-number">31</span> - i;</span> <span class="line" id="L1082"> <span class="tok-kw">try</span> testing.expectEqual(expected, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1083"> }</span> <span class="line" id="L1084"> }</span> <span class="line" id="L1085"></span> <span class="line" id="L1086"> <span class="tok-comment">// Constants</span> </span> <span class="line" id="L1087"> {</span> <span class="line" id="L1088"> stack_machine.reset();</span> <span class="line" id="L1089"> program.clearRetainingCapacity();</span> <span class="line" id="L1090"></span> <span class="line" id="L1091"> <span class="tok-kw">const</span> input = [_]<span class="tok-type">comptime_int</span>{</span> <span class="line" id="L1092"> <span class="tok-number">1</span>,</span> <span class="line" id="L1093"> -<span class="tok-number">1</span>,</span> <span class="line" id="L1094"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0x0fff</span>)),</span> <span class="line" id="L1095"> <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@truncate</span>(-<span class="tok-number">0x0fff</span>)),</span> <span class="line" id="L1096"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0x0fffffff</span>)),</span> <span class="line" id="L1097"> <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@truncate</span>(-<span class="tok-number">0x0fffffff</span>)),</span> <span class="line" id="L1098"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0x0fffffffffffffff</span>)),</span> <span class="line" id="L1099"> <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@truncate</span>(-<span class="tok-number">0x0fffffffffffffff</span>)),</span> <span class="line" id="L1100"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0x8000000</span>)),</span> <span class="line" id="L1101"> <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@truncate</span>(-<span class="tok-number">0x8000000</span>)),</span> <span class="line" id="L1102"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0x12345678_12345678</span>)),</span> <span class="line" id="L1103"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xffffffff_ffffffff</span>)),</span> <span class="line" id="L1104"> <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xeeeeeeee_eeeeeeee</span>)),</span> <span class="line" id="L1105"> };</span> <span class="line" id="L1106"></span> <span class="line" id="L1107"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, input[<span class="tok-number">0</span>]);</span> <span class="line" id="L1108"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i8</span>, input[<span class="tok-number">1</span>]);</span> <span class="line" id="L1109"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, input[<span class="tok-number">2</span>]);</span> <span class="line" id="L1110"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, input[<span class="tok-number">3</span>]);</span> <span class="line" id="L1111"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u32</span>, input[<span class="tok-number">4</span>]);</span> <span class="line" id="L1112"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i32</span>, input[<span class="tok-number">5</span>]);</span> <span class="line" id="L1113"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u64</span>, input[<span class="tok-number">6</span>]);</span> <span class="line" id="L1114"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i64</span>, input[<span class="tok-number">7</span>]);</span> <span class="line" id="L1115"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u28</span>, input[<span class="tok-number">8</span>]);</span> <span class="line" id="L1116"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i28</span>, input[<span class="tok-number">9</span>]);</span> <span class="line" id="L1117"> <span class="tok-kw">try</span> b.writeAddr(writer, input[<span class="tok-number">10</span>]);</span> <span class="line" id="L1118"></span> <span class="line" id="L1119"> <span class="tok-kw">var</span> mock_compile_unit: dwarf.CompileUnit = <span class="tok-null">undefined</span>;</span> <span class="line" id="L1120"> mock_compile_unit.addr_base = <span class="tok-number">1</span>;</span> <span class="line" id="L1121"></span> <span class="line" id="L1122"> <span class="tok-kw">var</span> mock_debug_addr = std.ArrayList(<span class="tok-type">u8</span>).init(allocator);</span> <span class="line" id="L1123"> <span class="tok-kw">defer</span> mock_debug_addr.deinit();</span> <span class="line" id="L1124"></span> <span class="line" id="L1125"> <span class="tok-kw">try</span> mock_debug_addr.writer().writeIntNative(<span class="tok-type">u16</span>, <span class="tok-number">0</span>);</span> <span class="line" id="L1126"> <span class="tok-kw">try</span> mock_debug_addr.writer().writeIntNative(<span class="tok-type">usize</span>, input[<span class="tok-number">11</span>]);</span> <span class="line" id="L1127"> <span class="tok-kw">try</span> mock_debug_addr.writer().writeIntNative(<span class="tok-type">usize</span>, input[<span class="tok-number">12</span>]);</span> <span class="line" id="L1128"></span> <span class="line" id="L1129"> <span class="tok-kw">const</span> context = ExpressionContext{</span> <span class="line" id="L1130"> .compile_unit = &amp;mock_compile_unit,</span> <span class="line" id="L1131"> .debug_addr = mock_debug_addr.items,</span> <span class="line" id="L1132"> };</span> <span class="line" id="L1133"></span> <span class="line" id="L1134"> <span class="tok-kw">try</span> b.writeConstx(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">1</span>));</span> <span class="line" id="L1135"> <span class="tok-kw">try</span> b.writeAddrx(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">1</span> + <span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>)));</span> <span class="line" id="L1136"></span> <span class="line" id="L1137"> <span class="tok-kw">const</span> die_offset: <span class="tok-type">usize</span> = <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xaabbccdd</span>);</span> <span class="line" id="L1138"> <span class="tok-kw">const</span> type_bytes: []<span class="tok-kw">const</span> <span class="tok-type">u8</span> = &amp;.{ <span class="tok-number">1</span>, <span class="tok-number">2</span>, <span class="tok-number">3</span>, <span class="tok-number">4</span> };</span> <span class="line" id="L1139"> <span class="tok-kw">try</span> b.writeConstType(writer, die_offset, type_bytes);</span> <span class="line" id="L1140"></span> <span class="line" id="L1141"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-number">0</span>);</span> <span class="line" id="L1142"></span> <span class="line" id="L1143"> <span class="tok-kw">const</span> const_type = stack_machine.stack.popOrNull().?.const_type;</span> <span class="line" id="L1144"> <span class="tok-kw">try</span> testing.expectEqual(die_offset, const_type.type_offset);</span> <span class="line" id="L1145"> <span class="tok-kw">try</span> testing.expectEqualSlices(<span class="tok-type">u8</span>, type_bytes, const_type.value_bytes);</span> <span class="line" id="L1146"></span> <span class="line" id="L1147"> <span class="tok-kw">const</span> expected = .{</span> <span class="line" id="L1148"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">12</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1149"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">11</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1150"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">10</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1151"> .{ <span class="tok-type">isize</span>, input[<span class="tok-number">9</span>], <span class="tok-type">isize</span> },</span> <span class="line" id="L1152"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">8</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1153"> .{ <span class="tok-type">isize</span>, input[<span class="tok-number">7</span>], <span class="tok-type">isize</span> },</span> <span class="line" id="L1154"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">6</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1155"> .{ <span class="tok-type">isize</span>, input[<span class="tok-number">5</span>], <span class="tok-type">isize</span> },</span> <span class="line" id="L1156"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">4</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1157"> .{ <span class="tok-type">isize</span>, input[<span class="tok-number">3</span>], <span class="tok-type">isize</span> },</span> <span class="line" id="L1158"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">2</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1159"> .{ <span class="tok-type">isize</span>, input[<span class="tok-number">1</span>], <span class="tok-type">isize</span> },</span> <span class="line" id="L1160"> .{ <span class="tok-type">usize</span>, input[<span class="tok-number">0</span>], <span class="tok-type">usize</span> },</span> <span class="line" id="L1161"> };</span> <span class="line" id="L1162"></span> <span class="line" id="L1163"> <span class="tok-kw">inline</span> <span class="tok-kw">for</span> (expected) |e| {</span> <span class="line" id="L1164"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(e[<span class="tok-number">0</span>], e[<span class="tok-number">1</span>]), <span class="tok-builtin">@as</span>(e[<span class="tok-number">2</span>], <span class="tok-builtin">@bitCast</span>(stack_machine.stack.popOrNull().?.generic)));</span> <span class="line" id="L1165"> }</span> <span class="line" id="L1166"> }</span> <span class="line" id="L1167"></span> <span class="line" id="L1168"> <span class="tok-comment">// Register values</span> </span> <span class="line" id="L1169"> <span class="tok-kw">if</span> (<span class="tok-builtin">@sizeOf</span>(std.debug.ThreadContext) != <span class="tok-number">0</span>) {</span> <span class="line" id="L1170"> stack_machine.reset();</span> <span class="line" id="L1171"> program.clearRetainingCapacity();</span> <span class="line" id="L1172"></span> <span class="line" id="L1173"> <span class="tok-kw">const</span> reg_context = abi.RegisterContext{</span> <span class="line" id="L1174"> .eh_frame = <span class="tok-null">true</span>,</span> <span class="line" id="L1175"> .is_macho = builtin.os.tag == .macos,</span> <span class="line" id="L1176"> };</span> <span class="line" id="L1177"> <span class="tok-kw">var</span> thread_context: std.debug.ThreadContext = <span class="tok-null">undefined</span>;</span> <span class="line" id="L1178"> std.debug.relocateContext(&amp;thread_context);</span> <span class="line" id="L1179"> <span class="tok-kw">const</span> context = ExpressionContext{</span> <span class="line" id="L1180"> .thread_context = &amp;thread_context,</span> <span class="line" id="L1181"> .reg_context = reg_context,</span> <span class="line" id="L1182"> };</span> <span class="line" id="L1183"></span> <span class="line" id="L1184"> <span class="tok-comment">// Only test register operations on arch / os that have them implemented</span> </span> <span class="line" id="L1185"> <span class="tok-kw">if</span> (abi.regBytes(&amp;thread_context, <span class="tok-number">0</span>, reg_context)) |reg_bytes| {</span> <span class="line" id="L1186"></span> <span class="line" id="L1187"> <span class="tok-comment">// TODO: Test fbreg (once implemented): mock a DIE and point compile_unit.frame_base at it</span> </span> <span class="line" id="L1188"></span> <span class="line" id="L1189"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, reg_bytes, <span class="tok-number">0xee</span>);</span> <span class="line" id="L1190"> (<span class="tok-kw">try</span> abi.regValueNative(<span class="tok-type">usize</span>, &amp;thread_context, abi.fpRegNum(reg_context), reg_context)).* = <span class="tok-number">1</span>;</span> <span class="line" id="L1191"> (<span class="tok-kw">try</span> abi.regValueNative(<span class="tok-type">usize</span>, &amp;thread_context, abi.spRegNum(reg_context), reg_context)).* = <span class="tok-number">2</span>;</span> <span class="line" id="L1192"> (<span class="tok-kw">try</span> abi.regValueNative(<span class="tok-type">usize</span>, &amp;thread_context, abi.ipRegNum(), reg_context)).* = <span class="tok-number">3</span>;</span> <span class="line" id="L1193"></span> <span class="line" id="L1194"> <span class="tok-kw">try</span> b.writeBreg(writer, abi.fpRegNum(reg_context), <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">100</span>));</span> <span class="line" id="L1195"> <span class="tok-kw">try</span> b.writeBreg(writer, abi.spRegNum(reg_context), <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">200</span>));</span> <span class="line" id="L1196"> <span class="tok-kw">try</span> b.writeBregx(writer, abi.ipRegNum(), <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">300</span>));</span> <span class="line" id="L1197"> <span class="tok-kw">try</span> b.writeRegvalType(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">u8</span>, <span class="tok-number">0</span>), <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">400</span>));</span> <span class="line" id="L1198"></span> <span class="line" id="L1199"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-number">0</span>);</span> <span class="line" id="L1200"></span> <span class="line" id="L1201"> <span class="tok-kw">const</span> regval_type = stack_machine.stack.popOrNull().?.regval_type;</span> <span class="line" id="L1202"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">400</span>), regval_type.type_offset);</span> <span class="line" id="L1203"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">u8</span>, <span class="tok-builtin">@sizeOf</span>(<span class="tok-type">usize</span>)), regval_type.type_size);</span> <span class="line" id="L1204"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xee</span>), regval_type.value);</span> <span class="line" id="L1205"></span> <span class="line" id="L1206"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">303</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1207"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">202</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1208"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">101</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1209"> } <span class="tok-kw">else</span> |err| {</span> <span class="line" id="L1210"> <span class="tok-kw">switch</span> (err) {</span> <span class="line" id="L1211"> <span class="tok-kw">error</span>.UnimplementedArch,</span> <span class="line" id="L1212"> <span class="tok-kw">error</span>.UnimplementedOs,</span> <span class="line" id="L1213"> <span class="tok-kw">error</span>.ThreadContextNotSupported,</span> <span class="line" id="L1214"> =&gt; {},</span> <span class="line" id="L1215"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> err,</span> <span class="line" id="L1216"> }</span> <span class="line" id="L1217"> }</span> <span class="line" id="L1218"> }</span> <span class="line" id="L1219"></span> <span class="line" id="L1220"> <span class="tok-comment">// Stack operations</span> </span> <span class="line" id="L1221"> {</span> <span class="line" id="L1222"> <span class="tok-kw">var</span> context = ExpressionContext{};</span> <span class="line" id="L1223"></span> <span class="line" id="L1224"> stack_machine.reset();</span> <span class="line" id="L1225"> program.clearRetainingCapacity();</span> <span class="line" id="L1226"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1227"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.dup);</span> <span class="line" id="L1228"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1229"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">1</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1230"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">1</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1231"></span> <span class="line" id="L1232"> stack_machine.reset();</span> <span class="line" id="L1233"> program.clearRetainingCapacity();</span> <span class="line" id="L1234"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1235"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.drop);</span> <span class="line" id="L1236"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1237"> <span class="tok-kw">try</span> testing.expect(stack_machine.stack.popOrNull() == <span class="tok-null">null</span>);</span> <span class="line" id="L1238"></span> <span class="line" id="L1239"> stack_machine.reset();</span> <span class="line" id="L1240"> program.clearRetainingCapacity();</span> <span class="line" id="L1241"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">4</span>);</span> <span class="line" id="L1242"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">5</span>);</span> <span class="line" id="L1243"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">6</span>);</span> <span class="line" id="L1244"> <span class="tok-kw">try</span> b.writePick(writer, <span class="tok-number">2</span>);</span> <span class="line" id="L1245"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1246"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">4</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1247"></span> <span class="line" id="L1248"> stack_machine.reset();</span> <span class="line" id="L1249"> program.clearRetainingCapacity();</span> <span class="line" id="L1250"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">4</span>);</span> <span class="line" id="L1251"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">5</span>);</span> <span class="line" id="L1252"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">6</span>);</span> <span class="line" id="L1253"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.over);</span> <span class="line" id="L1254"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1255"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">5</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1256"></span> <span class="line" id="L1257"> stack_machine.reset();</span> <span class="line" id="L1258"> program.clearRetainingCapacity();</span> <span class="line" id="L1259"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">5</span>);</span> <span class="line" id="L1260"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">6</span>);</span> <span class="line" id="L1261"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.swap);</span> <span class="line" id="L1262"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1263"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">5</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1264"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">6</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1265"></span> <span class="line" id="L1266"> stack_machine.reset();</span> <span class="line" id="L1267"> program.clearRetainingCapacity();</span> <span class="line" id="L1268"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">4</span>);</span> <span class="line" id="L1269"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">5</span>);</span> <span class="line" id="L1270"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u8</span>, <span class="tok-number">6</span>);</span> <span class="line" id="L1271"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.rot);</span> <span class="line" id="L1272"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1273"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">5</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1274"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">4</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1275"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">6</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1276"></span> <span class="line" id="L1277"> <span class="tok-kw">const</span> deref_target: <span class="tok-type">usize</span> = <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xffeeffee_ffeeffee</span>);</span> <span class="line" id="L1278"></span> <span class="line" id="L1279"> stack_machine.reset();</span> <span class="line" id="L1280"> program.clearRetainingCapacity();</span> <span class="line" id="L1281"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1282"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.deref);</span> <span class="line" id="L1283"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1284"> <span class="tok-kw">try</span> testing.expectEqual(deref_target, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1285"></span> <span class="line" id="L1286"> stack_machine.reset();</span> <span class="line" id="L1287"> program.clearRetainingCapacity();</span> <span class="line" id="L1288"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1289"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1290"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.xderef);</span> <span class="line" id="L1291"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1292"> <span class="tok-kw">try</span> testing.expectEqual(deref_target, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1293"></span> <span class="line" id="L1294"> stack_machine.reset();</span> <span class="line" id="L1295"> program.clearRetainingCapacity();</span> <span class="line" id="L1296"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1297"> <span class="tok-kw">try</span> b.writeDerefSize(writer, <span class="tok-number">1</span>);</span> <span class="line" id="L1298"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1299"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u8</span>, <span class="tok-builtin">@ptrCast</span>(&amp;deref_target)).*), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1300"></span> <span class="line" id="L1301"> stack_machine.reset();</span> <span class="line" id="L1302"> program.clearRetainingCapacity();</span> <span class="line" id="L1303"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1304"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1305"> <span class="tok-kw">try</span> b.writeXDerefSize(writer, <span class="tok-number">1</span>);</span> <span class="line" id="L1306"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1307"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u8</span>, <span class="tok-builtin">@ptrCast</span>(&amp;deref_target)).*), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1308"></span> <span class="line" id="L1309"> <span class="tok-kw">const</span> type_offset: <span class="tok-type">usize</span> = <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xaabbaabb_aabbaabb</span>);</span> <span class="line" id="L1310"></span> <span class="line" id="L1311"> stack_machine.reset();</span> <span class="line" id="L1312"> program.clearRetainingCapacity();</span> <span class="line" id="L1313"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1314"> <span class="tok-kw">try</span> b.writeDerefType(writer, <span class="tok-number">1</span>, type_offset);</span> <span class="line" id="L1315"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1316"> <span class="tok-kw">const</span> deref_type = stack_machine.stack.popOrNull().?.regval_type;</span> <span class="line" id="L1317"> <span class="tok-kw">try</span> testing.expectEqual(type_offset, deref_type.type_offset);</span> <span class="line" id="L1318"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">u8</span>, <span class="tok-number">1</span>), deref_type.type_size);</span> <span class="line" id="L1319"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u8</span>, <span class="tok-builtin">@ptrCast</span>(&amp;deref_target)).*), deref_type.value);</span> <span class="line" id="L1320"></span> <span class="line" id="L1321"> stack_machine.reset();</span> <span class="line" id="L1322"> program.clearRetainingCapacity();</span> <span class="line" id="L1323"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1324"> <span class="tok-kw">try</span> b.writeAddr(writer, <span class="tok-builtin">@intFromPtr</span>(&amp;deref_target));</span> <span class="line" id="L1325"> <span class="tok-kw">try</span> b.writeXDerefType(writer, <span class="tok-number">1</span>, type_offset);</span> <span class="line" id="L1326"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1327"> <span class="tok-kw">const</span> xderef_type = stack_machine.stack.popOrNull().?.regval_type;</span> <span class="line" id="L1328"> <span class="tok-kw">try</span> testing.expectEqual(type_offset, xderef_type.type_offset);</span> <span class="line" id="L1329"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">u8</span>, <span class="tok-number">1</span>), xderef_type.type_size);</span> <span class="line" id="L1330"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@as</span>(*<span class="tok-kw">const</span> <span class="tok-type">u8</span>, <span class="tok-builtin">@ptrCast</span>(&amp;deref_target)).*), xderef_type.value);</span> <span class="line" id="L1331"></span> <span class="line" id="L1332"> context.object_address = &amp;deref_target;</span> <span class="line" id="L1333"></span> <span class="line" id="L1334"> stack_machine.reset();</span> <span class="line" id="L1335"> program.clearRetainingCapacity();</span> <span class="line" id="L1336"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.push_object_address);</span> <span class="line" id="L1337"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1338"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@intFromPtr</span>(context.object_address.?)), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1339"></span> <span class="line" id="L1340"> <span class="tok-comment">// TODO: Test OP.form_tls_address</span> </span> <span class="line" id="L1341"></span> <span class="line" id="L1342"> context.cfa = <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xccddccdd_ccddccdd</span>);</span> <span class="line" id="L1343"></span> <span class="line" id="L1344"> stack_machine.reset();</span> <span class="line" id="L1345"> program.clearRetainingCapacity();</span> <span class="line" id="L1346"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.call_frame_cfa);</span> <span class="line" id="L1347"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1348"> <span class="tok-kw">try</span> testing.expectEqual(context.cfa.?, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1349"> }</span> <span class="line" id="L1350"></span> <span class="line" id="L1351"> <span class="tok-comment">// Arithmetic and Logical Operations</span> </span> <span class="line" id="L1352"> {</span> <span class="line" id="L1353"> <span class="tok-kw">var</span> context = ExpressionContext{};</span> <span class="line" id="L1354"></span> <span class="line" id="L1355"> stack_machine.reset();</span> <span class="line" id="L1356"> program.clearRetainingCapacity();</span> <span class="line" id="L1357"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, -<span class="tok-number">4096</span>);</span> <span class="line" id="L1358"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.abs);</span> <span class="line" id="L1359"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1360"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">4096</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1361"></span> <span class="line" id="L1362"> stack_machine.reset();</span> <span class="line" id="L1363"> program.clearRetainingCapacity();</span> <span class="line" id="L1364"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xff0f</span>);</span> <span class="line" id="L1365"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xf0ff</span>);</span> <span class="line" id="L1366"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.@&quot;and&quot;);</span> <span class="line" id="L1367"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1368"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xf00f</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1369"></span> <span class="line" id="L1370"> stack_machine.reset();</span> <span class="line" id="L1371"> program.clearRetainingCapacity();</span> <span class="line" id="L1372"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, -<span class="tok-number">404</span>);</span> <span class="line" id="L1373"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, <span class="tok-number">100</span>);</span> <span class="line" id="L1374"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.div);</span> <span class="line" id="L1375"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1376"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, -<span class="tok-number">404</span> / <span class="tok-number">100</span>), <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@bitCast</span>(stack_machine.stack.popOrNull().?.generic)));</span> <span class="line" id="L1377"></span> <span class="line" id="L1378"> stack_machine.reset();</span> <span class="line" id="L1379"> program.clearRetainingCapacity();</span> <span class="line" id="L1380"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">200</span>);</span> <span class="line" id="L1381"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">50</span>);</span> <span class="line" id="L1382"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.minus);</span> <span class="line" id="L1383"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1384"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">150</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1385"></span> <span class="line" id="L1386"> stack_machine.reset();</span> <span class="line" id="L1387"> program.clearRetainingCapacity();</span> <span class="line" id="L1388"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">123</span>);</span> <span class="line" id="L1389"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">100</span>);</span> <span class="line" id="L1390"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.mod);</span> <span class="line" id="L1391"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1392"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">23</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1393"></span> <span class="line" id="L1394"> stack_machine.reset();</span> <span class="line" id="L1395"> program.clearRetainingCapacity();</span> <span class="line" id="L1396"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xff</span>);</span> <span class="line" id="L1397"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xee</span>);</span> <span class="line" id="L1398"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.mul);</span> <span class="line" id="L1399"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1400"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xed12</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1401"></span> <span class="line" id="L1402"> stack_machine.reset();</span> <span class="line" id="L1403"> program.clearRetainingCapacity();</span> <span class="line" id="L1404"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">5</span>);</span> <span class="line" id="L1405"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.neg);</span> <span class="line" id="L1406"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, -<span class="tok-number">6</span>);</span> <span class="line" id="L1407"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.neg);</span> <span class="line" id="L1408"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1409"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">6</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1410"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, -<span class="tok-number">5</span>), <span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-builtin">@bitCast</span>(stack_machine.stack.popOrNull().?.generic)));</span> <span class="line" id="L1411"></span> <span class="line" id="L1412"> stack_machine.reset();</span> <span class="line" id="L1413"> program.clearRetainingCapacity();</span> <span class="line" id="L1414"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xff0f</span>);</span> <span class="line" id="L1415"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.not);</span> <span class="line" id="L1416"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1417"> <span class="tok-kw">try</span> testing.expectEqual(~<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xff0f</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1418"></span> <span class="line" id="L1419"> stack_machine.reset();</span> <span class="line" id="L1420"> program.clearRetainingCapacity();</span> <span class="line" id="L1421"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xff0f</span>);</span> <span class="line" id="L1422"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xf0ff</span>);</span> <span class="line" id="L1423"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.@&quot;or&quot;);</span> <span class="line" id="L1424"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1425"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xffff</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1426"></span> <span class="line" id="L1427"> stack_machine.reset();</span> <span class="line" id="L1428"> program.clearRetainingCapacity();</span> <span class="line" id="L1429"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, <span class="tok-number">402</span>);</span> <span class="line" id="L1430"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">i16</span>, <span class="tok-number">100</span>);</span> <span class="line" id="L1431"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.plus);</span> <span class="line" id="L1432"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1433"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">502</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1434"></span> <span class="line" id="L1435"> stack_machine.reset();</span> <span class="line" id="L1436"> program.clearRetainingCapacity();</span> <span class="line" id="L1437"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">4096</span>);</span> <span class="line" id="L1438"> <span class="tok-kw">try</span> b.writePlusUconst(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">8192</span>));</span> <span class="line" id="L1439"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1440"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">4096</span> + <span class="tok-number">8192</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1441"></span> <span class="line" id="L1442"> stack_machine.reset();</span> <span class="line" id="L1443"> program.clearRetainingCapacity();</span> <span class="line" id="L1444"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xfff</span>);</span> <span class="line" id="L1445"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1446"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.shl);</span> <span class="line" id="L1447"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1448"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xfff</span> &lt;&lt; <span class="tok-number">1</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1449"></span> <span class="line" id="L1450"> stack_machine.reset();</span> <span class="line" id="L1451"> program.clearRetainingCapacity();</span> <span class="line" id="L1452"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xfff</span>);</span> <span class="line" id="L1453"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1454"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.shr);</span> <span class="line" id="L1455"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1456"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xfff</span> &gt;&gt; <span class="tok-number">1</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1457"></span> <span class="line" id="L1458"> stack_machine.reset();</span> <span class="line" id="L1459"> program.clearRetainingCapacity();</span> <span class="line" id="L1460"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xfff</span>);</span> <span class="line" id="L1461"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1462"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.shr);</span> <span class="line" id="L1463"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1464"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-builtin">@bitCast</span>(<span class="tok-builtin">@as</span>(<span class="tok-type">isize</span>, <span class="tok-number">0xfff</span>) &gt;&gt; <span class="tok-number">1</span>)), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1465"></span> <span class="line" id="L1466"> stack_machine.reset();</span> <span class="line" id="L1467"> program.clearRetainingCapacity();</span> <span class="line" id="L1468"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xf0ff</span>);</span> <span class="line" id="L1469"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0xff0f</span>);</span> <span class="line" id="L1470"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.xor);</span> <span class="line" id="L1471"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1472"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0x0ff0</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1473"> }</span> <span class="line" id="L1474"></span> <span class="line" id="L1475"> <span class="tok-comment">// Control Flow Operations</span> </span> <span class="line" id="L1476"> {</span> <span class="line" id="L1477"> <span class="tok-kw">var</span> context = ExpressionContext{};</span> <span class="line" id="L1478"> <span class="tok-kw">const</span> expected = .{</span> <span class="line" id="L1479"> .{ OP.le, <span class="tok-number">1</span>, <span class="tok-number">1</span>, <span class="tok-number">0</span> },</span> <span class="line" id="L1480"> .{ OP.ge, <span class="tok-number">1</span>, <span class="tok-number">0</span>, <span class="tok-number">1</span> },</span> <span class="line" id="L1481"> .{ OP.eq, <span class="tok-number">1</span>, <span class="tok-number">0</span>, <span class="tok-number">0</span> },</span> <span class="line" id="L1482"> .{ OP.lt, <span class="tok-number">0</span>, <span class="tok-number">1</span>, <span class="tok-number">0</span> },</span> <span class="line" id="L1483"> .{ OP.gt, <span class="tok-number">0</span>, <span class="tok-number">0</span>, <span class="tok-number">1</span> },</span> <span class="line" id="L1484"> .{ OP.ne, <span class="tok-number">0</span>, <span class="tok-number">1</span>, <span class="tok-number">1</span> },</span> <span class="line" id="L1485"> };</span> <span class="line" id="L1486"></span> <span class="line" id="L1487"> <span class="tok-kw">inline</span> <span class="tok-kw">for</span> (expected) |e| {</span> <span class="line" id="L1488"> stack_machine.reset();</span> <span class="line" id="L1489"> program.clearRetainingCapacity();</span> <span class="line" id="L1490"></span> <span class="line" id="L1491"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0</span>);</span> <span class="line" id="L1492"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0</span>);</span> <span class="line" id="L1493"> <span class="tok-kw">try</span> b.writeOpcode(writer, e[<span class="tok-number">0</span>]);</span> <span class="line" id="L1494"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0</span>);</span> <span class="line" id="L1495"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1496"> <span class="tok-kw">try</span> b.writeOpcode(writer, e[<span class="tok-number">0</span>]);</span> <span class="line" id="L1497"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">1</span>);</span> <span class="line" id="L1498"> <span class="tok-kw">try</span> b.writeConst(writer, <span class="tok-type">u16</span>, <span class="tok-number">0</span>);</span> <span class="line" id="L1499"> <span class="tok-kw">try</span> b.writeOpcode(writer, e[<span class="tok-number">0</span>]);</span> <span class="line" id="L1500"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1501"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, e[<span class="tok-number">3</span>]), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1502"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, e[<span class="tok-number">2</span>]), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1503"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, e[<span class="tok-number">1</span>]), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1504"> }</span> <span class="line" id="L1505"></span> <span class="line" id="L1506"> stack_machine.reset();</span> <span class="line" id="L1507"> program.clearRetainingCapacity();</span> <span class="line" id="L1508"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">2</span>);</span> <span class="line" id="L1509"> <span class="tok-kw">try</span> b.writeSkip(writer, <span class="tok-number">1</span>);</span> <span class="line" id="L1510"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">3</span>);</span> <span class="line" id="L1511"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1512"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">2</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1513"></span> <span class="line" id="L1514"> stack_machine.reset();</span> <span class="line" id="L1515"> program.clearRetainingCapacity();</span> <span class="line" id="L1516"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">2</span>);</span> <span class="line" id="L1517"> <span class="tok-kw">try</span> b.writeBra(writer, <span class="tok-number">1</span>);</span> <span class="line" id="L1518"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">3</span>);</span> <span class="line" id="L1519"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1520"> <span class="tok-kw">try</span> b.writeBra(writer, <span class="tok-number">1</span>);</span> <span class="line" id="L1521"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">4</span>);</span> <span class="line" id="L1522"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">5</span>);</span> <span class="line" id="L1523"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1524"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">5</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1525"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">4</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1526"> <span class="tok-kw">try</span> testing.expect(stack_machine.stack.popOrNull() == <span class="tok-null">null</span>);</span> <span class="line" id="L1527"></span> <span class="line" id="L1528"> <span class="tok-comment">// TODO: Test call2, call4, call_ref once implemented</span> </span> <span class="line" id="L1529"></span> <span class="line" id="L1530"> }</span> <span class="line" id="L1531"></span> <span class="line" id="L1532"> <span class="tok-comment">// Type conversions</span> </span> <span class="line" id="L1533"> {</span> <span class="line" id="L1534"> <span class="tok-kw">var</span> context = ExpressionContext{};</span> <span class="line" id="L1535"> stack_machine.reset();</span> <span class="line" id="L1536"> program.clearRetainingCapacity();</span> <span class="line" id="L1537"></span> <span class="line" id="L1538"> <span class="tok-comment">// TODO: Test typed OP.convert once implemented</span> </span> <span class="line" id="L1539"></span> <span class="line" id="L1540"> <span class="tok-kw">const</span> value: <span class="tok-type">usize</span> = <span class="tok-builtin">@truncate</span>(<span class="tok-number">0xffeeffee_ffeeffee</span>);</span> <span class="line" id="L1541"> <span class="tok-kw">var</span> value_bytes: [options.addr_size]<span class="tok-type">u8</span> = <span class="tok-null">undefined</span>;</span> <span class="line" id="L1542"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, &amp;value_bytes, value);</span> <span class="line" id="L1543"></span> <span class="line" id="L1544"> <span class="tok-comment">// Convert to generic type</span> </span> <span class="line" id="L1545"> stack_machine.reset();</span> <span class="line" id="L1546"> program.clearRetainingCapacity();</span> <span class="line" id="L1547"> <span class="tok-kw">try</span> b.writeConstType(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0</span>), &amp;value_bytes);</span> <span class="line" id="L1548"> <span class="tok-kw">try</span> b.writeConvert(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0</span>));</span> <span class="line" id="L1549"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1550"> <span class="tok-kw">try</span> testing.expectEqual(value, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1551"></span> <span class="line" id="L1552"> <span class="tok-comment">// Reinterpret to generic type</span> </span> <span class="line" id="L1553"> stack_machine.reset();</span> <span class="line" id="L1554"> program.clearRetainingCapacity();</span> <span class="line" id="L1555"> <span class="tok-kw">try</span> b.writeConstType(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0</span>), &amp;value_bytes);</span> <span class="line" id="L1556"> <span class="tok-kw">try</span> b.writeReinterpret(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0</span>));</span> <span class="line" id="L1557"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1558"> <span class="tok-kw">try</span> testing.expectEqual(value, stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1559"></span> <span class="line" id="L1560"> <span class="tok-comment">// Reinterpret to new type</span> </span> <span class="line" id="L1561"> <span class="tok-kw">const</span> die_offset: <span class="tok-type">usize</span> = <span class="tok-number">0xffee</span>;</span> <span class="line" id="L1562"></span> <span class="line" id="L1563"> stack_machine.reset();</span> <span class="line" id="L1564"> program.clearRetainingCapacity();</span> <span class="line" id="L1565"> <span class="tok-kw">try</span> b.writeConstType(writer, <span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0</span>), &amp;value_bytes);</span> <span class="line" id="L1566"> <span class="tok-kw">try</span> b.writeReinterpret(writer, die_offset);</span> <span class="line" id="L1567"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1568"> <span class="tok-kw">const</span> const_type = stack_machine.stack.popOrNull().?.const_type;</span> <span class="line" id="L1569"> <span class="tok-kw">try</span> testing.expectEqual(die_offset, const_type.type_offset);</span> <span class="line" id="L1570"></span> <span class="line" id="L1571"> stack_machine.reset();</span> <span class="line" id="L1572"> program.clearRetainingCapacity();</span> <span class="line" id="L1573"> <span class="tok-kw">try</span> b.writeLiteral(writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1574"> <span class="tok-kw">try</span> b.writeReinterpret(writer, die_offset);</span> <span class="line" id="L1575"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1576"> <span class="tok-kw">const</span> regval_type = stack_machine.stack.popOrNull().?.regval_type;</span> <span class="line" id="L1577"> <span class="tok-kw">try</span> testing.expectEqual(die_offset, regval_type.type_offset);</span> <span class="line" id="L1578"> }</span> <span class="line" id="L1579"></span> <span class="line" id="L1580"> <span class="tok-comment">// Special operations</span> </span> <span class="line" id="L1581"> {</span> <span class="line" id="L1582"> <span class="tok-kw">var</span> context = ExpressionContext{};</span> <span class="line" id="L1583"></span> <span class="line" id="L1584"> stack_machine.reset();</span> <span class="line" id="L1585"> program.clearRetainingCapacity();</span> <span class="line" id="L1586"> <span class="tok-kw">try</span> b.writeOpcode(writer, OP.nop);</span> <span class="line" id="L1587"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1588"> <span class="tok-kw">try</span> testing.expect(stack_machine.stack.popOrNull() == <span class="tok-null">null</span>);</span> <span class="line" id="L1589"></span> <span class="line" id="L1590"> <span class="tok-comment">// Sub-expression</span> </span> <span class="line" id="L1591"> {</span> <span class="line" id="L1592"> <span class="tok-kw">var</span> sub_program = std.ArrayList(<span class="tok-type">u8</span>).init(allocator);</span> <span class="line" id="L1593"> <span class="tok-kw">defer</span> sub_program.deinit();</span> <span class="line" id="L1594"> <span class="tok-kw">const</span> sub_writer = sub_program.writer();</span> <span class="line" id="L1595"> <span class="tok-kw">try</span> b.writeLiteral(sub_writer, <span class="tok-number">3</span>);</span> <span class="line" id="L1596"></span> <span class="line" id="L1597"> stack_machine.reset();</span> <span class="line" id="L1598"> program.clearRetainingCapacity();</span> <span class="line" id="L1599"> <span class="tok-kw">try</span> b.writeEntryValue(writer, sub_program.items);</span> <span class="line" id="L1600"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1601"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">3</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1602"> }</span> <span class="line" id="L1603"></span> <span class="line" id="L1604"> <span class="tok-comment">// Register location description</span> </span> <span class="line" id="L1605"> <span class="tok-kw">const</span> reg_context = abi.RegisterContext{</span> <span class="line" id="L1606"> .eh_frame = <span class="tok-null">true</span>,</span> <span class="line" id="L1607"> .is_macho = builtin.os.tag == .macos,</span> <span class="line" id="L1608"> };</span> <span class="line" id="L1609"> <span class="tok-kw">var</span> thread_context: std.debug.ThreadContext = <span class="tok-null">undefined</span>;</span> <span class="line" id="L1610"> std.debug.relocateContext(&amp;thread_context);</span> <span class="line" id="L1611"> context = ExpressionContext{</span> <span class="line" id="L1612"> .thread_context = &amp;thread_context,</span> <span class="line" id="L1613"> .reg_context = reg_context,</span> <span class="line" id="L1614"> };</span> <span class="line" id="L1615"></span> <span class="line" id="L1616"> <span class="tok-kw">if</span> (abi.regBytes(&amp;thread_context, <span class="tok-number">0</span>, reg_context)) |reg_bytes| {</span> <span class="line" id="L1617"> mem.writeIntSliceNative(<span class="tok-type">usize</span>, reg_bytes, <span class="tok-number">0xee</span>);</span> <span class="line" id="L1618"></span> <span class="line" id="L1619"> <span class="tok-kw">var</span> sub_program = std.ArrayList(<span class="tok-type">u8</span>).init(allocator);</span> <span class="line" id="L1620"> <span class="tok-kw">defer</span> sub_program.deinit();</span> <span class="line" id="L1621"> <span class="tok-kw">const</span> sub_writer = sub_program.writer();</span> <span class="line" id="L1622"> <span class="tok-kw">try</span> b.writeReg(sub_writer, <span class="tok-number">0</span>);</span> <span class="line" id="L1623"></span> <span class="line" id="L1624"> stack_machine.reset();</span> <span class="line" id="L1625"> program.clearRetainingCapacity();</span> <span class="line" id="L1626"> <span class="tok-kw">try</span> b.writeEntryValue(writer, sub_program.items);</span> <span class="line" id="L1627"> _ = <span class="tok-kw">try</span> stack_machine.run(program.items, allocator, context, <span class="tok-null">null</span>);</span> <span class="line" id="L1628"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-builtin">@as</span>(<span class="tok-type">usize</span>, <span class="tok-number">0xee</span>), stack_machine.stack.popOrNull().?.generic);</span> <span class="line" id="L1629"> } <span class="tok-kw">else</span> |err| {</span> <span class="line" id="L1630"> <span class="tok-kw">switch</span> (err) {</span> <span class="line" id="L1631"> <span class="tok-kw">error</span>.UnimplementedArch,</span> <span class="line" id="L1632"> <span class="tok-kw">error</span>.UnimplementedOs,</span> <span class="line" id="L1633"> <span class="tok-kw">error</span>.ThreadContextNotSupported,</span> <span class="line" id="L1634"> =&gt; {},</span> <span class="line" id="L1635"> <span class="tok-kw">else</span> =&gt; <span class="tok-kw">return</span> err,</span> <span class="line" id="L1636"> }</span> <span class="line" id="L1637"> }</span> <span class="line" id="L1638"> }</span> <span class="line" id="L1639">}</span> <span class="line" id="L1640"></span> </code></pre></body> </html>
0
repos/yazap/docs/src/std
repos/yazap/docs/src/std/time/epoch.zig.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>time/epoch.zig - source view</title> <link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAPNJREFUeNpi/P//PwMlgOXHUjly9E0G4hwgZmQiQZMqEK8H4v9QzUEgQSaoADK+zhH9iAGL+C0gDoAaNg9mGLoLfgA1awK9hS9gzgJxA9RQBmQDrgMxJzRMGKE4HYj/Ial5A8QmQLwCJoBsgBYW2+TR1ChDaWt4LOBxKsi/VUh8XiD+gq4IVyzwQAMJBoKwacZlAB8Qf0bi96IZhtOAe1D6LpqaEiz6rmEzQAeIzwGxCJpieFqApo/vQKyJboAaEBsAsSEupwI1MwKjGBTVHOhegMX5UajYRqiBjMgYmj400cVh0XgTiKdC0zhJgJHS7AwQYABm9EAdCKrEfAAAAABJRU5ErkJggg=="/> <style> body{ font-family: system-ui, -apple-system, Roboto, "Segoe UI", sans-serif; margin: 0; line-height: 1.5; } pre > code { display: block; overflow: auto; line-height: normal; margin: 0em; } .tok-kw { color: #333; font-weight: bold; } .tok-str { color: #d14; } .tok-builtin { color: #005C7A; } .tok-comment { color: #545454; font-style: italic; } .tok-fn { color: #900; font-weight: bold; } .tok-null { color: #005C5C; } .tok-number { color: #005C5C; } .tok-type { color: #458; font-weight: bold; } pre { counter-reset: line; } pre .line:before { counter-increment: line; content: counter(line); display: inline-block; padding-right: 1em; width: 2em; text-align: right; color: #999; } .line { width: 100%; display: inline-block; } .line:target { border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; background: #fafafa; } @media (prefers-color-scheme: dark) { body{ background:#222; color: #ccc; } pre > code { color: #ccc; background: #222; border: unset; } .line:target { border-top: 1px solid #444; border-bottom: 1px solid #444; background: #333; } .tok-kw { color: #eee; } .tok-str { color: #2e5; } .tok-builtin { color: #ff894c; } .tok-comment { color: #aa7; } .tok-fn { color: #B1A0F8; } .tok-null { color: #ff8080; } .tok-number { color: #ff8080; } .tok-type { color: #68f; } } </style> </head> <body> <pre><code><span class="line" id="L1"><span class="tok-comment">//! Epoch reference times in terms of their difference from</span></span> <span class="line" id="L2"><span class="tok-comment">//! UTC 1970-01-01 in seconds.</span></span> <span class="line" id="L3"><span class="tok-kw">const</span> std = <span class="tok-builtin">@import</span>(<span class="tok-str">&quot;../std.zig&quot;</span>);</span> <span class="line" id="L4"><span class="tok-kw">const</span> testing = std.testing;</span> <span class="line" id="L5"><span class="tok-kw">const</span> math = std.math;</span> <span class="line" id="L6"></span> <span class="line" id="L7"><span class="tok-comment">/// Jan 01, 1970 AD</span></span> <span class="line" id="L8"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> posix = <span class="tok-number">0</span>;</span> <span class="line" id="L9"><span class="tok-comment">/// Jan 01, 1980 AD</span></span> <span class="line" id="L10"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> dos = <span class="tok-number">315532800</span>;</span> <span class="line" id="L11"><span class="tok-comment">/// Jan 01, 2001 AD</span></span> <span class="line" id="L12"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ios = <span class="tok-number">978307200</span>;</span> <span class="line" id="L13"><span class="tok-comment">/// Nov 17, 1858 AD</span></span> <span class="line" id="L14"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> openvms = -<span class="tok-number">3506716800</span>;</span> <span class="line" id="L15"><span class="tok-comment">/// Jan 01, 1900 AD</span></span> <span class="line" id="L16"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> zos = -<span class="tok-number">2208988800</span>;</span> <span class="line" id="L17"><span class="tok-comment">/// Jan 01, 1601 AD</span></span> <span class="line" id="L18"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> windows = -<span class="tok-number">11644473600</span>;</span> <span class="line" id="L19"><span class="tok-comment">/// Jan 01, 1978 AD</span></span> <span class="line" id="L20"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> amiga = <span class="tok-number">252460800</span>;</span> <span class="line" id="L21"><span class="tok-comment">/// Dec 31, 1967 AD</span></span> <span class="line" id="L22"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> pickos = -<span class="tok-number">63244800</span>;</span> <span class="line" id="L23"><span class="tok-comment">/// Jan 06, 1980 AD</span></span> <span class="line" id="L24"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> gps = <span class="tok-number">315964800</span>;</span> <span class="line" id="L25"><span class="tok-comment">/// Jan 01, 0001 AD</span></span> <span class="line" id="L26"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> clr = -<span class="tok-number">62135769600</span>;</span> <span class="line" id="L27"></span> <span class="line" id="L28"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> unix = posix;</span> <span class="line" id="L29"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> android = posix;</span> <span class="line" id="L30"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> os2 = dos;</span> <span class="line" id="L31"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> bios = dos;</span> <span class="line" id="L32"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> vfat = dos;</span> <span class="line" id="L33"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ntfs = windows;</span> <span class="line" id="L34"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> ntp = zos;</span> <span class="line" id="L35"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> jbase = pickos;</span> <span class="line" id="L36"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> aros = amiga;</span> <span class="line" id="L37"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> morphos = amiga;</span> <span class="line" id="L38"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> brew = gps;</span> <span class="line" id="L39"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> atsc = gps;</span> <span class="line" id="L40"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> go = clr;</span> <span class="line" id="L41"></span> <span class="line" id="L42"><span class="tok-comment">/// The type that holds the current year, i.e. 2016</span></span> <span class="line" id="L43"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Year = <span class="tok-type">u16</span>;</span> <span class="line" id="L44"></span> <span class="line" id="L45"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> epoch_year = <span class="tok-number">1970</span>;</span> <span class="line" id="L46"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> secs_per_day: <span class="tok-type">u17</span> = <span class="tok-number">24</span> * <span class="tok-number">60</span> * <span class="tok-number">60</span>;</span> <span class="line" id="L47"></span> <span class="line" id="L48"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">isLeapYear</span>(year: Year) <span class="tok-type">bool</span> {</span> <span class="line" id="L49"> <span class="tok-kw">if</span> (<span class="tok-builtin">@mod</span>(year, <span class="tok-number">4</span>) != <span class="tok-number">0</span>)</span> <span class="line" id="L50"> <span class="tok-kw">return</span> <span class="tok-null">false</span>;</span> <span class="line" id="L51"> <span class="tok-kw">if</span> (<span class="tok-builtin">@mod</span>(year, <span class="tok-number">100</span>) != <span class="tok-number">0</span>)</span> <span class="line" id="L52"> <span class="tok-kw">return</span> <span class="tok-null">true</span>;</span> <span class="line" id="L53"> <span class="tok-kw">return</span> (<span class="tok-number">0</span> == <span class="tok-builtin">@mod</span>(year, <span class="tok-number">400</span>));</span> <span class="line" id="L54">}</span> <span class="line" id="L55"></span> <span class="line" id="L56"><span class="tok-kw">test</span> <span class="tok-str">&quot;isLeapYear&quot;</span> {</span> <span class="line" id="L57"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-null">false</span>, isLeapYear(<span class="tok-number">2095</span>));</span> <span class="line" id="L58"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-null">true</span>, isLeapYear(<span class="tok-number">2096</span>));</span> <span class="line" id="L59"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-null">false</span>, isLeapYear(<span class="tok-number">2100</span>));</span> <span class="line" id="L60"> <span class="tok-kw">try</span> testing.expectEqual(<span class="tok-null">true</span>, isLeapYear(<span class="tok-number">2400</span>));</span> <span class="line" id="L61">}</span> <span class="line" id="L62"></span> <span class="line" id="L63"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getDaysInYear</span>(year: Year) <span class="tok-type">u9</span> {</span> <span class="line" id="L64"> <span class="tok-kw">return</span> <span class="tok-kw">if</span> (isLeapYear(year)) <span class="tok-number">366</span> <span class="tok-kw">else</span> <span class="tok-number">365</span>;</span> <span class="line" id="L65">}</span> <span class="line" id="L66"></span> <span class="line" id="L67"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> YearLeapKind = <span class="tok-kw">enum</span>(<span class="tok-type">u1</span>) { not_leap, leap };</span> <span class="line" id="L68"></span> <span class="line" id="L69"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> Month = <span class="tok-kw">enum</span>(<span class="tok-type">u4</span>) {</span> <span class="line" id="L70"> jan = <span class="tok-number">1</span>,</span> <span class="line" id="L71"> feb,</span> <span class="line" id="L72"> mar,</span> <span class="line" id="L73"> apr,</span> <span class="line" id="L74"> may,</span> <span class="line" id="L75"> jun,</span> <span class="line" id="L76"> jul,</span> <span class="line" id="L77"> aug,</span> <span class="line" id="L78"> sep,</span> <span class="line" id="L79"> oct,</span> <span class="line" id="L80"> nov,</span> <span class="line" id="L81"> dec,</span> <span class="line" id="L82"></span> <span class="line" id="L83"> <span class="tok-comment">/// return the numeric calendar value for the given month</span></span> <span class="line" id="L84"> <span class="tok-comment">/// i.e. jan=1, feb=2, etc</span></span> <span class="line" id="L85"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">numeric</span>(self: Month) <span class="tok-type">u4</span> {</span> <span class="line" id="L86"> <span class="tok-kw">return</span> <span class="tok-builtin">@intFromEnum</span>(self);</span> <span class="line" id="L87"> }</span> <span class="line" id="L88">};</span> <span class="line" id="L89"></span> <span class="line" id="L90"><span class="tok-comment">/// Get the number of days in the given month</span></span> <span class="line" id="L91"><span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getDaysInMonth</span>(leap_year: YearLeapKind, month: Month) <span class="tok-type">u5</span> {</span> <span class="line" id="L92"> <span class="tok-kw">return</span> <span class="tok-kw">switch</span> (month) {</span> <span class="line" id="L93"> .jan =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L94"> .feb =&gt; <span class="tok-builtin">@as</span>(<span class="tok-type">u5</span>, <span class="tok-kw">switch</span> (leap_year) {</span> <span class="line" id="L95"> .leap =&gt; <span class="tok-number">29</span>,</span> <span class="line" id="L96"> .not_leap =&gt; <span class="tok-number">28</span>,</span> <span class="line" id="L97"> }),</span> <span class="line" id="L98"> .mar =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L99"> .apr =&gt; <span class="tok-number">30</span>,</span> <span class="line" id="L100"> .may =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L101"> .jun =&gt; <span class="tok-number">30</span>,</span> <span class="line" id="L102"> .jul =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L103"> .aug =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L104"> .sep =&gt; <span class="tok-number">30</span>,</span> <span class="line" id="L105"> .oct =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L106"> .nov =&gt; <span class="tok-number">30</span>,</span> <span class="line" id="L107"> .dec =&gt; <span class="tok-number">31</span>,</span> <span class="line" id="L108"> };</span> <span class="line" id="L109">}</span> <span class="line" id="L110"></span> <span class="line" id="L111"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> YearAndDay = <span class="tok-kw">struct</span> {</span> <span class="line" id="L112"> year: Year,</span> <span class="line" id="L113"> <span class="tok-comment">/// The number of days into the year (0 to 365)</span></span> <span class="line" id="L114"> day: <span class="tok-type">u9</span>,</span> <span class="line" id="L115"></span> <span class="line" id="L116"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">calculateMonthDay</span>(self: YearAndDay) MonthAndDay {</span> <span class="line" id="L117"> <span class="tok-kw">var</span> month: Month = .jan;</span> <span class="line" id="L118"> <span class="tok-kw">var</span> days_left = self.day;</span> <span class="line" id="L119"> <span class="tok-kw">const</span> leap_kind: YearLeapKind = <span class="tok-kw">if</span> (isLeapYear(self.year)) .leap <span class="tok-kw">else</span> .not_leap;</span> <span class="line" id="L120"> <span class="tok-kw">while</span> (<span class="tok-null">true</span>) {</span> <span class="line" id="L121"> <span class="tok-kw">const</span> days_in_month = getDaysInMonth(leap_kind, month);</span> <span class="line" id="L122"> <span class="tok-kw">if</span> (days_left &lt; days_in_month)</span> <span class="line" id="L123"> <span class="tok-kw">break</span>;</span> <span class="line" id="L124"> days_left -= days_in_month;</span> <span class="line" id="L125"> month = <span class="tok-builtin">@as</span>(Month, <span class="tok-builtin">@enumFromInt</span>(<span class="tok-builtin">@intFromEnum</span>(month) + <span class="tok-number">1</span>));</span> <span class="line" id="L126"> }</span> <span class="line" id="L127"> <span class="tok-kw">return</span> .{ .month = month, .day_index = <span class="tok-builtin">@as</span>(<span class="tok-type">u5</span>, <span class="tok-builtin">@intCast</span>(days_left)) };</span> <span class="line" id="L128"> }</span> <span class="line" id="L129">};</span> <span class="line" id="L130"></span> <span class="line" id="L131"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> MonthAndDay = <span class="tok-kw">struct</span> {</span> <span class="line" id="L132"> month: Month,</span> <span class="line" id="L133"> day_index: <span class="tok-type">u5</span>, <span class="tok-comment">// days into the month (0 to 30)</span> </span> <span class="line" id="L134">};</span> <span class="line" id="L135"></span> <span class="line" id="L136"><span class="tok-comment">// days since epoch Oct 1, 1970</span> </span> <span class="line" id="L137"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> EpochDay = <span class="tok-kw">struct</span> {</span> <span class="line" id="L138"> day: <span class="tok-type">u47</span>, <span class="tok-comment">// u47 = u64 - u17 (because day = sec(u64) / secs_per_day(u17)</span> </span> <span class="line" id="L139"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">calculateYearDay</span>(self: EpochDay) YearAndDay {</span> <span class="line" id="L140"> <span class="tok-kw">var</span> year_day = self.day;</span> <span class="line" id="L141"> <span class="tok-kw">var</span> year: Year = epoch_year;</span> <span class="line" id="L142"> <span class="tok-kw">while</span> (<span class="tok-null">true</span>) {</span> <span class="line" id="L143"> <span class="tok-kw">const</span> year_size = getDaysInYear(year);</span> <span class="line" id="L144"> <span class="tok-kw">if</span> (year_day &lt; year_size)</span> <span class="line" id="L145"> <span class="tok-kw">break</span>;</span> <span class="line" id="L146"> year_day -= year_size;</span> <span class="line" id="L147"> year += <span class="tok-number">1</span>;</span> <span class="line" id="L148"> }</span> <span class="line" id="L149"> <span class="tok-kw">return</span> .{ .year = year, .day = <span class="tok-builtin">@as</span>(<span class="tok-type">u9</span>, <span class="tok-builtin">@intCast</span>(year_day)) };</span> <span class="line" id="L150"> }</span> <span class="line" id="L151">};</span> <span class="line" id="L152"></span> <span class="line" id="L153"><span class="tok-comment">/// seconds since start of day</span></span> <span class="line" id="L154"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> DaySeconds = <span class="tok-kw">struct</span> {</span> <span class="line" id="L155"> secs: <span class="tok-type">u17</span>, <span class="tok-comment">// max is 24*60*60 = 86400</span> </span> <span class="line" id="L156"></span> <span class="line" id="L157"> <span class="tok-comment">/// the number of hours past the start of the day (0 to 23)</span></span> <span class="line" id="L158"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getHoursIntoDay</span>(self: DaySeconds) <span class="tok-type">u5</span> {</span> <span class="line" id="L159"> <span class="tok-kw">return</span> <span class="tok-builtin">@as</span>(<span class="tok-type">u5</span>, <span class="tok-builtin">@intCast</span>(<span class="tok-builtin">@divTrunc</span>(self.secs, <span class="tok-number">3600</span>)));</span> <span class="line" id="L160"> }</span> <span class="line" id="L161"> <span class="tok-comment">/// the number of minutes past the hour (0 to 59)</span></span> <span class="line" id="L162"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getMinutesIntoHour</span>(self: DaySeconds) <span class="tok-type">u6</span> {</span> <span class="line" id="L163"> <span class="tok-kw">return</span> <span class="tok-builtin">@as</span>(<span class="tok-type">u6</span>, <span class="tok-builtin">@intCast</span>(<span class="tok-builtin">@divTrunc</span>(<span class="tok-builtin">@mod</span>(self.secs, <span class="tok-number">3600</span>), <span class="tok-number">60</span>)));</span> <span class="line" id="L164"> }</span> <span class="line" id="L165"> <span class="tok-comment">/// the number of seconds past the start of the minute (0 to 59)</span></span> <span class="line" id="L166"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getSecondsIntoMinute</span>(self: DaySeconds) <span class="tok-type">u6</span> {</span> <span class="line" id="L167"> <span class="tok-kw">return</span> math.comptimeMod(self.secs, <span class="tok-number">60</span>);</span> <span class="line" id="L168"> }</span> <span class="line" id="L169">};</span> <span class="line" id="L170"></span> <span class="line" id="L171"><span class="tok-comment">/// seconds since epoch Oct 1, 1970 at 12:00 AM</span></span> <span class="line" id="L172"><span class="tok-kw">pub</span> <span class="tok-kw">const</span> EpochSeconds = <span class="tok-kw">struct</span> {</span> <span class="line" id="L173"> secs: <span class="tok-type">u64</span>,</span> <span class="line" id="L174"></span> <span class="line" id="L175"> <span class="tok-comment">/// Returns the number of days since the epoch as an EpochDay.</span></span> <span class="line" id="L176"> <span class="tok-comment">/// Use EpochDay to get information about the day of this time.</span></span> <span class="line" id="L177"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getEpochDay</span>(self: EpochSeconds) EpochDay {</span> <span class="line" id="L178"> <span class="tok-kw">return</span> EpochDay{ .day = <span class="tok-builtin">@as</span>(<span class="tok-type">u47</span>, <span class="tok-builtin">@intCast</span>(<span class="tok-builtin">@divTrunc</span>(self.secs, secs_per_day))) };</span> <span class="line" id="L179"> }</span> <span class="line" id="L180"></span> <span class="line" id="L181"> <span class="tok-comment">/// Returns the number of seconds into the day as DaySeconds.</span></span> <span class="line" id="L182"> <span class="tok-comment">/// Use DaySeconds to get information about the time.</span></span> <span class="line" id="L183"> <span class="tok-kw">pub</span> <span class="tok-kw">fn</span> <span class="tok-fn">getDaySeconds</span>(self: EpochSeconds) DaySeconds {</span> <span class="line" id="L184"> <span class="tok-kw">return</span> DaySeconds{ .secs = math.comptimeMod(self.secs, secs_per_day) };</span> <span class="line" id="L185"> }</span> <span class="line" id="L186">};</span> <span class="line" id="L187"></span> <span class="line" id="L188"><span class="tok-kw">fn</span> <span class="tok-fn">testEpoch</span>(secs: <span class="tok-type">u64</span>, expected_year_day: YearAndDay, expected_month_day: MonthAndDay, expected_day_seconds: <span class="tok-kw">struct</span> {</span> <span class="line" id="L189"> <span class="tok-comment">/// 0 to 23</span></span> <span class="line" id="L190"> hours_into_day: <span class="tok-type">u5</span>,</span> <span class="line" id="L191"> <span class="tok-comment">/// 0 to 59</span></span> <span class="line" id="L192"> minutes_into_hour: <span class="tok-type">u6</span>,</span> <span class="line" id="L193"> <span class="tok-comment">/// 0 to 59</span></span> <span class="line" id="L194"> seconds_into_minute: <span class="tok-type">u6</span>,</span> <span class="line" id="L195">}) !<span class="tok-type">void</span> {</span> <span class="line" id="L196"> <span class="tok-kw">const</span> epoch_seconds = EpochSeconds{ .secs = secs };</span> <span class="line" id="L197"> <span class="tok-kw">const</span> epoch_day = epoch_seconds.getEpochDay();</span> <span class="line" id="L198"> <span class="tok-kw">const</span> day_seconds = epoch_seconds.getDaySeconds();</span> <span class="line" id="L199"> <span class="tok-kw">const</span> year_day = epoch_day.calculateYearDay();</span> <span class="line" id="L200"> <span class="tok-kw">try</span> testing.expectEqual(expected_year_day, year_day);</span> <span class="line" id="L201"> <span class="tok-kw">try</span> testing.expectEqual(expected_month_day, year_day.calculateMonthDay());</span> <span class="line" id="L202"> <span class="tok-kw">try</span> testing.expectEqual(expected_day_seconds.hours_into_day, day_seconds.getHoursIntoDay());</span> <span class="line" id="L203"> <span class="tok-kw">try</span> testing.expectEqual(expected_day_seconds.minutes_into_hour, day_seconds.getMinutesIntoHour());</span> <span class="line" id="L204"> <span class="tok-kw">try</span> testing.expectEqual(expected_day_seconds.seconds_into_minute, day_seconds.getSecondsIntoMinute());</span> <span class="line" id="L205">}</span> <span class="line" id="L206"></span> <span class="line" id="L207"><span class="tok-kw">test</span> <span class="tok-str">&quot;epoch decoding&quot;</span> {</span> <span class="line" id="L208"> <span class="tok-kw">try</span> testEpoch(<span class="tok-number">0</span>, .{ .year = <span class="tok-number">1970</span>, .day = <span class="tok-number">0</span> }, .{</span> <span class="line" id="L209"> .month = .jan,</span> <span class="line" id="L210"> .day_index = <span class="tok-number">0</span>,</span> <span class="line" id="L211"> }, .{ .hours_into_day = <span class="tok-number">0</span>, .minutes_into_hour = <span class="tok-number">0</span>, .seconds_into_minute = <span class="tok-number">0</span> });</span> <span class="line" id="L212"></span> <span class="line" id="L213"> <span class="tok-kw">try</span> testEpoch(<span class="tok-number">31535999</span>, .{ .year = <span class="tok-number">1970</span>, .day = <span class="tok-number">364</span> }, .{</span> <span class="line" id="L214"> .month = .dec,</span> <span class="line" id="L215"> .day_index = <span class="tok-number">30</span>,</span> <span class="line" id="L216"> }, .{ .hours_into_day = <span class="tok-number">23</span>, .minutes_into_hour = <span class="tok-number">59</span>, .seconds_into_minute = <span class="tok-number">59</span> });</span> <span class="line" id="L217"></span> <span class="line" id="L218"> <span class="tok-kw">try</span> testEpoch(<span class="tok-number">1622924906</span>, .{ .year = <span class="tok-number">2021</span>, .day = <span class="tok-number">31</span> + <span class="tok-number">28</span> + <span class="tok-number">31</span> + <span class="tok-number">30</span> + <span class="tok-number">31</span> + <span class="tok-number">4</span> }, .{</span> <span class="line" id="L219"> .month = .jun,</span> <span class="line" id="L220"> .day_index = <span class="tok-number">4</span>,</span> <span class="line" id="L221"> }, .{ .hours_into_day = <span class="tok-number">20</span>, .minutes_into_hour = <span class="tok-number">28</span>, .seconds_into_minute = <span class="tok-number">26</span> });</span> <span class="line" id="L222"></span> <span class="line" id="L223"> <span class="tok-kw">try</span> testEpoch(<span class="tok-number">1625159473</span>, .{ .year = <span class="tok-number">2021</span>, .day = <span class="tok-number">31</span> + <span class="tok-number">28</span> + <span class="tok-number">31</span> + <span class="tok-number">30</span> + <span class="tok-number">31</span> + <span class="tok-number">30</span> }, .{</span> <span class="line" id="L224"> .month = .jul,</span> <span class="line" id="L225"> .day_index = <span class="tok-number">0</span>,</span> <span class="line" id="L226"> }, .{ .hours_into_day = <span class="tok-number">17</span>, .minutes_into_hour = <span class="tok-number">11</span>, .seconds_into_minute = <span class="tok-number">13</span> });</span> <span class="line" id="L227">}</span> <span class="line" id="L228"></span> </code></pre></body> </html>
0
repos
repos/ly/build.zig.zon
.{ .name = "ly", .version = "1.0.0", .minimum_zig_version = "0.12.0", .dependencies = .{ .clap = .{ .url = "https://github.com/Hejsil/zig-clap/archive/refs/tags/0.9.1.tar.gz", .hash = "122062d301a203d003547b414237229b09a7980095061697349f8bef41be9c30266b", }, .zigini = .{ .url = "https://github.com/Kawaii-Ash/zigini/archive/0bba97a12582928e097f4074cc746c43351ba4c8.tar.gz", .hash = "12209b971367b4066d40ecad4728e6fdffc4cc4f19356d424c2de57f5b69ac7a619a", }, }, .paths = .{""}, }
0
repos
repos/ly/build.zig
const std = @import("std"); const builtin = @import("builtin"); const PatchMap = std.StringHashMap([]const u8); const min_zig_string = "0.12.0"; const current_zig = builtin.zig_version; // Implementing zig version detection through compile time comptime { const min_zig = std.SemanticVersion.parse(min_zig_string) catch unreachable; if (current_zig.order(min_zig) == .lt) { @compileError(std.fmt.comptimePrint("Your Zig version v{} does not meet the minimum build requirement of v{}", .{ current_zig, min_zig })); } } const ly_version = std.SemanticVersion{ .major = 1, .minor = 1, .patch = 0 }; var dest_directory: []const u8 = undefined; var config_directory: []const u8 = undefined; var prefix_directory: []const u8 = undefined; var executable_name: []const u8 = undefined; var default_tty_str: []const u8 = undefined; const ProgressNode = if (current_zig.minor == 12) *std.Progress.Node else std.Progress.Node; pub fn build(b: *std.Build) !void { dest_directory = b.option([]const u8, "dest_directory", "Specify a destination directory for installation") orelse ""; config_directory = b.option([]const u8, "config_directory", "Specify a default config directory (default is /etc). This path gets embedded into the binary") orelse "/etc"; prefix_directory = b.option([]const u8, "prefix_directory", "Specify a default prefix directory (default is /usr)") orelse "/usr"; executable_name = b.option([]const u8, "name", "Specify installed executable file name (default is ly)") orelse "ly"; const bin_directory = try b.allocator.dupe(u8, config_directory); config_directory = try std.fs.path.join(b.allocator, &[_][]const u8{ dest_directory, config_directory }); const build_options = b.addOptions(); const version_str = try getVersionStr(b, "ly", ly_version); const enable_x11_support = b.option(bool, "enable_x11_support", "Enable X11 support (default is on)") orelse true; const default_tty = b.option(u8, "default_tty", "Set the TTY (default is 2)") orelse 2; default_tty_str = try std.fmt.allocPrint(b.allocator, "{d}", .{default_tty}); build_options.addOption([]const u8, "config_directory", bin_directory); build_options.addOption([]const u8, "prefix_directory", prefix_directory); build_options.addOption([]const u8, "version", version_str); build_options.addOption(u8, "tty", default_tty); build_options.addOption(bool, "enable_x11_support", enable_x11_support); const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "ly", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const zigini = b.dependency("zigini", .{ .target = target, .optimize = optimize }); exe.root_module.addImport("zigini", zigini.module("zigini")); exe.root_module.addOptions("build_options", build_options); const clap = b.dependency("clap", .{ .target = target, .optimize = optimize }); exe.root_module.addImport("clap", clap.module("clap")); exe.addIncludePath(b.path("include")); exe.linkSystemLibrary("pam"); if (enable_x11_support) exe.linkSystemLibrary("xcb"); exe.linkLibC(); const translate_c = b.addTranslateC(.{ .root_source_file = b.path("include/termbox2.h"), .target = target, .optimize = optimize, }); translate_c.defineCMacroRaw("TB_IMPL"); const termbox2 = translate_c.addModule("termbox2"); exe.root_module.addImport("termbox2", termbox2); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const installexe_step = b.step("installexe", "Install Ly"); installexe_step.makeFn = ExeInstaller(true).make; installexe_step.dependOn(b.getInstallStep()); const installnoconf_step = b.step("installnoconf", "Install Ly without its configuration file"); installnoconf_step.makeFn = ExeInstaller(false).make; installnoconf_step.dependOn(b.getInstallStep()); const installsystemd_step = b.step("installsystemd", "Install the Ly systemd service"); installsystemd_step.makeFn = ServiceInstaller(.Systemd).make; installsystemd_step.dependOn(installexe_step); const installopenrc_step = b.step("installopenrc", "Install the Ly openrc service"); installopenrc_step.makeFn = ServiceInstaller(.Openrc).make; installopenrc_step.dependOn(installexe_step); const installrunit_step = b.step("installrunit", "Install the Ly runit service"); installrunit_step.makeFn = ServiceInstaller(.Runit).make; installrunit_step.dependOn(installexe_step); const installs6_step = b.step("installs6", "Install the Ly s6 service"); installs6_step.makeFn = ServiceInstaller(.S6).make; installs6_step.dependOn(installexe_step); const installdinit_step = b.step("installdinit", "Install the Ly dinit service"); installdinit_step.makeFn = ServiceInstaller(.Dinit).make; installdinit_step.dependOn(installexe_step); const uninstallall_step = b.step("uninstallall", "Uninstall Ly and all services"); uninstallall_step.makeFn = uninstallall; } pub fn ExeInstaller(install_conf: bool) type { return struct { pub fn make(step: *std.Build.Step, _: ProgressNode) !void { try install_ly(step.owner.allocator, install_conf); } }; } const InitSystem = enum { Systemd, Openrc, Runit, S6, Dinit, }; pub fn ServiceInstaller(comptime init_system: InitSystem) type { return struct { pub fn make(step: *std.Build.Step, _: ProgressNode) !void { const allocator = step.owner.allocator; var patch_map = PatchMap.init(allocator); defer patch_map.deinit(); try patch_map.put("$DEFAULT_TTY", default_tty_str); try patch_map.put("$CONFIG_DIRECTORY", config_directory); try patch_map.put("$PREFIX_DIRECTORY", prefix_directory); try patch_map.put("$EXECUTABLE_NAME", executable_name); switch (init_system) { .Systemd => { const service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/lib/systemd/system" }); std.fs.cwd().makePath(service_path) catch {}; var service_dir = std.fs.cwd().openDir(service_path, .{}) catch unreachable; defer service_dir.close(); const patched_service = try patchFile(allocator, "res/ly.service", patch_map); try installText(patched_service, service_dir, service_path, "ly.service", .{ .mode = 0o644 }); }, .Openrc => { const service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/init.d" }); std.fs.cwd().makePath(service_path) catch {}; var service_dir = std.fs.cwd().openDir(service_path, .{}) catch unreachable; defer service_dir.close(); const patched_service = try patchFile(allocator, "res/ly-openrc", patch_map); try installText(patched_service, service_dir, service_path, executable_name, .{ .mode = 0o755 }); }, .Runit => { const service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/sv/ly" }); std.fs.cwd().makePath(service_path) catch {}; var service_dir = std.fs.cwd().openDir(service_path, .{}) catch unreachable; defer service_dir.close(); const supervise_path = try std.fs.path.join(allocator, &[_][]const u8{ service_path, "supervise" }); const patched_conf = try patchFile(allocator, "res/ly-runit-service/conf", patch_map); try installText(patched_conf, service_dir, service_path, "conf", .{}); try installFile("res/ly-runit-service/finish", service_dir, service_path, "finish", .{ .override_mode = 0o755 }); const patched_run = try patchFile(allocator, "res/ly-runit-service/run", patch_map); try installText(patched_run, service_dir, service_path, "run", .{ .mode = 0o755 }); try std.fs.cwd().symLink("/run/runit/supervise.ly", supervise_path, .{}); std.debug.print("info: installed symlink /run/runit/supervise.ly\n", .{}); }, .S6 => { const admin_service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/adminsv/default/contents.d" }); std.fs.cwd().makePath(admin_service_path) catch {}; var admin_service_dir = std.fs.cwd().openDir(admin_service_path, .{}) catch unreachable; defer admin_service_dir.close(); const file = try admin_service_dir.createFile("ly-srv", .{}); file.close(); const service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/sv/ly-srv" }); std.fs.cwd().makePath(service_path) catch {}; var service_dir = std.fs.cwd().openDir(service_path, .{}) catch unreachable; defer service_dir.close(); const patched_run = try patchFile(allocator, "res/ly-s6/run", patch_map); try installText(patched_run, service_dir, service_path, "run", .{ .mode = 0o755 }); try installFile("res/ly-s6/type", service_dir, service_path, "type", .{}); }, .Dinit => { const service_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/dinit.d" }); std.fs.cwd().makePath(service_path) catch {}; var service_dir = std.fs.cwd().openDir(service_path, .{}) catch unreachable; defer service_dir.close(); const patched_service = try patchFile(allocator, "res/ly-dinit", patch_map); try installText(patched_service, service_dir, service_path, "ly", .{}); }, } } }; } fn install_ly(allocator: std.mem.Allocator, install_config: bool) !void { const ly_config_directory = try std.fs.path.join(allocator, &[_][]const u8{ config_directory, "/ly" }); std.fs.cwd().makePath(ly_config_directory) catch { std.debug.print("warn: {s} already exists as a directory.\n", .{ly_config_directory}); }; const ly_lang_path = try std.fs.path.join(allocator, &[_][]const u8{ config_directory, "/ly/lang" }); std.fs.cwd().makePath(ly_lang_path) catch { std.debug.print("warn: {s} already exists as a directory.\n", .{config_directory}); }; { const exe_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin" }); if (!std.mem.eql(u8, dest_directory, "")) { std.fs.cwd().makePath(exe_path) catch { std.debug.print("warn: {s} already exists as a directory.\n", .{exe_path}); }; } var executable_dir = std.fs.cwd().openDir(exe_path, .{}) catch unreachable; defer executable_dir.close(); try installFile("zig-out/bin/ly", executable_dir, exe_path, executable_name, .{}); } { var config_dir = std.fs.cwd().openDir(ly_config_directory, .{}) catch unreachable; defer config_dir.close(); if (install_config) { var patch_map = PatchMap.init(allocator); defer patch_map.deinit(); try patch_map.put("$DEFAULT_TTY", default_tty_str); try patch_map.put("$CONFIG_DIRECTORY", config_directory); try patch_map.put("$PREFIX_DIRECTORY", prefix_directory); const patched_config = try patchFile(allocator, "res/config.ini", patch_map); try installText(patched_config, config_dir, ly_config_directory, "config.ini", .{}); } { var patch_map = PatchMap.init(allocator); defer patch_map.deinit(); try patch_map.put("$CONFIG_DIRECTORY", config_directory); const patched_setup = try patchFile(allocator, "res/setup.sh", patch_map); try installText(patched_setup, config_dir, ly_config_directory, "setup.sh", .{ .mode = 0o755 }); } } { var lang_dir = std.fs.cwd().openDir(ly_lang_path, .{}) catch unreachable; defer lang_dir.close(); try installFile("res/lang/cat.ini", lang_dir, ly_lang_path, "cat.ini", .{}); try installFile("res/lang/cs.ini", lang_dir, ly_lang_path, "cs.ini", .{}); try installFile("res/lang/de.ini", lang_dir, ly_lang_path, "de.ini", .{}); try installFile("res/lang/en.ini", lang_dir, ly_lang_path, "en.ini", .{}); try installFile("res/lang/es.ini", lang_dir, ly_lang_path, "es.ini", .{}); try installFile("res/lang/fr.ini", lang_dir, ly_lang_path, "fr.ini", .{}); try installFile("res/lang/it.ini", lang_dir, ly_lang_path, "it.ini", .{}); try installFile("res/lang/pl.ini", lang_dir, ly_lang_path, "pl.ini", .{}); try installFile("res/lang/pt.ini", lang_dir, ly_lang_path, "pt.ini", .{}); try installFile("res/lang/pt_BR.ini", lang_dir, ly_lang_path, "pt_BR.ini", .{}); try installFile("res/lang/ro.ini", lang_dir, ly_lang_path, "ro.ini", .{}); try installFile("res/lang/ru.ini", lang_dir, ly_lang_path, "ru.ini", .{}); try installFile("res/lang/sr.ini", lang_dir, ly_lang_path, "sr.ini", .{}); try installFile("res/lang/sv.ini", lang_dir, ly_lang_path, "sv.ini", .{}); try installFile("res/lang/tr.ini", lang_dir, ly_lang_path, "tr.ini", .{}); try installFile("res/lang/uk.ini", lang_dir, ly_lang_path, "uk.ini", .{}); } { const pam_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/pam.d" }); if (!std.mem.eql(u8, dest_directory, "")) { std.fs.cwd().makePath(pam_path) catch { std.debug.print("warn: {s} already exists as a directory.\n", .{pam_path}); }; } var pam_dir = std.fs.cwd().openDir(pam_path, .{}) catch unreachable; defer pam_dir.close(); try installFile("res/pam.d/ly", pam_dir, pam_path, "ly", .{ .override_mode = 0o644 }); } } pub fn uninstallall(step: *std.Build.Step, _: ProgressNode) !void { const allocator = step.owner.allocator; try deleteTree(allocator, config_directory, "/ly", "ly config directory not found"); const exe_path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin/", executable_name }); var success = true; std.fs.cwd().deleteFile(exe_path) catch { std.debug.print("warn: ly executable not found\n", .{}); success = false; }; if (success) std.debug.print("info: deleted {s}\n", .{exe_path}); try deleteFile(allocator, config_directory, "/pam.d/ly", "ly pam file not found"); try deleteFile(allocator, prefix_directory, "/lib/systemd/system/ly.service", "systemd service not found"); try deleteFile(allocator, config_directory, "/init.d/ly", "openrc service not found"); try deleteTree(allocator, config_directory, "/sv/ly", "runit service not found"); try deleteTree(allocator, config_directory, "/s6/sv/ly-srv", "s6 service not found"); try deleteFile(allocator, config_directory, "/s6/adminsv/default/contents.d/ly-srv", "s6 admin service not found"); try deleteFile(allocator, config_directory, "/dinit.d/ly", "dinit service not found"); } fn getVersionStr(b: *std.Build, name: []const u8, version: std.SemanticVersion) ![]const u8 { const version_str = b.fmt("{d}.{d}.{d}", .{ version.major, version.minor, version.patch }); var status: u8 = undefined; const git_describe_raw = b.runAllowFail(&[_][]const u8{ "git", "-C", b.build_root.path orelse ".", "describe", "--match", "*.*.*", "--tags", }, &status, .Ignore) catch { return version_str; }; var git_describe = std.mem.trim(u8, git_describe_raw, " \n\r"); git_describe = std.mem.trimLeft(u8, git_describe, "v"); switch (std.mem.count(u8, git_describe, "-")) { 0 => { if (!std.mem.eql(u8, version_str, git_describe)) { std.debug.print("{s} version '{s}' does not match git tag: '{s}'\n", .{ name, version_str, git_describe }); std.process.exit(1); } return version_str; }, 2 => { // Untagged development build (e.g. 0.10.0-dev.2025+ecf0050a9). var it = std.mem.splitScalar(u8, git_describe, '-'); const tagged_ancestor = std.mem.trimLeft(u8, it.first(), "v"); const commit_height = it.next().?; const commit_id = it.next().?; const ancestor_ver = try std.SemanticVersion.parse(tagged_ancestor); if (version.order(ancestor_ver) != .gt) { std.debug.print("{s} version '{}' must be greater than tagged ancestor '{}'\n", .{ name, version, ancestor_ver }); std.process.exit(1); } // Check that the commit hash is prefixed with a 'g' (a Git convention). if (commit_id.len < 1 or commit_id[0] != 'g') { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); return version_str; } // The version is reformatted in accordance with the https://semver.org specification. return b.fmt("{s}-dev.{s}+{s}", .{ version_str, commit_height, commit_id[1..] }); }, else => { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); return version_str; }, } } fn installFile( source_file: []const u8, destination_directory: std.fs.Dir, destination_directory_path: []const u8, destination_file: []const u8, options: std.fs.Dir.CopyFileOptions, ) !void { try std.fs.cwd().copyFile(source_file, destination_directory, destination_file, options); std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); } fn patchFile(allocator: std.mem.Allocator, source_file: []const u8, patch_map: PatchMap) ![]const u8 { var file = try std.fs.cwd().openFile(source_file, .{}); defer file.close(); const reader = file.reader(); var text = try reader.readAllAlloc(allocator, std.math.maxInt(u16)); var iterator = patch_map.iterator(); while (iterator.next()) |kv| { const new_text = try std.mem.replaceOwned(u8, allocator, text, kv.key_ptr.*, kv.value_ptr.*); allocator.free(text); text = new_text; } return text; } fn installText( text: []const u8, destination_directory: std.fs.Dir, destination_directory_path: []const u8, destination_file: []const u8, options: std.fs.File.CreateFlags, ) !void { var file = try destination_directory.createFile(destination_file, options); defer file.close(); const writer = file.writer(); try writer.writeAll(text); std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); } fn deleteFile( allocator: std.mem.Allocator, prefix: []const u8, file: []const u8, warning: []const u8, ) !void { const path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, prefix, file }); std.fs.cwd().deleteFile(path) catch |err| { if (err == error.FileNotFound) { std.debug.print("warn: {s}\n", .{warning}); return; } return err; }; std.debug.print("info: deleted {s}\n", .{path}); } fn deleteTree( allocator: std.mem.Allocator, prefix: []const u8, directory: []const u8, warning: []const u8, ) !void { const path = try std.fs.path.join(allocator, &[_][]const u8{ dest_directory, prefix, directory }); var dir = std.fs.cwd().openDir(path, .{}) catch |err| { if (err == error.FileNotFound) { std.debug.print("warn: {s}\n", .{warning}); return; } return err; }; dir.close(); try std.fs.cwd().deleteTree(path); std.debug.print("info: deleted {s}\n", .{path}); }
0
repos
repos/ly/license.md
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar <[email protected]> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.
0
repos
repos/ly/readme.md
# Ly - a TUI display manager ![Ly screenshot](.github/screenshot.png "Ly screenshot") Ly is a lightweight TUI (ncurses-like) display manager for Linux and BSD. ## Dependencies - Compile-time: - zig >=0.12.0 - libc - pam - xcb (optional, required by default; needed for X11 support) - Runtime (with default config): - xorg - xorg-xauth - shutdown ### Debian ``` # apt install build-essential libpam0g-dev libxcb-xkb-dev ``` ### Fedora **Warning**: You may encounter issues with SELinux on Fedora. It is recommended to add a rule for Ly as it currently does not ship one. ``` # dnf install kernel-devel pam-devel libxcb-devel ``` ## Support The following desktop environments were tested with success: - awesome - bspwm - budgie - cinnamon - cosmic - deepin - dwl - dwm - enlightenment - gnome - i3 - kde - labwc - lxde - lxqt - mate - maxx - pantheon - qtile - spectrwm - sway - windowmaker - xfce - xmonad Ly should work with any X desktop environment, and provides basic wayland support (sway works very well, for example). ## systemd? Unlike what you may have heard, Ly does not require `systemd`, and was even specifically designed not to depend on `logind`. You should be able to make it work easily with a better init, changing the source code won't be necessary :) ## Cloning and Compiling Clone the repository ``` $ git clone https://github.com/fairyglade/ly ``` Change the directory to ly ``` $ cd ly ``` Compile ``` $ zig build ``` Test in the configured tty (tty2 by default) or a terminal emulator (but desktop environments won't start) ``` # zig build run ``` Install Ly and the provided systemd service file ``` # zig build installsystemd ``` Enable the service ``` # systemctl enable ly.service ``` If you need to switch between ttys after Ly's start you also have to disable getty on Ly's tty to prevent "login" from spawning on top of it ``` # systemctl disable [email protected] ``` ### OpenRC **NOTE 1**: On Gentoo, Ly will disable the `display-manager-init` service in order to run. Clone, compile and test. Install Ly and the provided OpenRC service ``` # zig build installopenrc ``` Enable the service ``` # rc-update add ly ``` You can edit which tty Ly will start on by editing the `tty` option in the configuration file. If you choose a tty that already has a login/getty running (has a basic login prompt), then you have to disable getty, so it doesn't respawn on top of ly ``` # rc-update del agetty.tty2 ``` **NOTE 2**: To avoid a console spawning on top on Ly, comment out the appropriate line from /etc/inittab (default is 2). ### runit ``` # zig build installrunit # ln -s /etc/sv/ly /var/service/ ``` By default, ly will run on tty2. To change the tty it must be set in `/etc/ly/config.ini` You should as well disable your existing display manager service if needed, e.g.: ``` # rm /var/service/lxdm ``` The agetty service for the tty console where you are running ly should be disabled. For instance, if you are running ly on tty2 (that's the default, check your `/etc/ly/config.ini`) you should disable the agetty-tty2 service like this: ``` # rm /var/service/agetty-tty2 ``` ### s6 ``` # zig build installs6 ``` Then, edit `/etc/s6/config/ttyX.conf` and set `SPAWN="no"`, where X is the TTY ID (e.g. `2`). Finally, enable the service: ``` # s6-service add default ly-srv # s6-db-reload # s6-rc -u change ly-srv ``` ### dinit ``` # zig build installdinit # dinitctl enable ly ``` In addition to the steps above, you will also have to keep a TTY free within `/etc/dinit.d/config/console.conf`. To do that, change `ACTIVE_CONSOLES` so that the tty that ly should use in `/etc/ly/config.ini` is free. ### Updating You can also install Ly without copying the system service and the configuration file. That's called *updating*. To update, simply run: ``` # zig build installnoconf ``` If you want to also copy the default config file (but still not the system service), run: ``` # zig build installexe ``` ## Arch Linux Installation You can install ly from the [`[extra]` repos](https://archlinux.org/packages/extra/x86_64/ly/): ``` $ sudo pacman -S ly ``` ## Gentoo Installation You can install ly from the GURU repository: Note: If the package is masked, you may need to unmask it using ~amd64 keyword: ```bash # echo 'x11-misc/ly ~amd64' >> /etc/portage/package.accept_keywords ``` 1. Enable the GURU repository: ```bash # eselect repository enable guru ``` 2. Sync the GURU repository: ```bash # emaint sync -r guru ``` 3. Install ly from source: ```bash # emerge --ask x11-misc/ly ``` ## Configuration You can find all the configuration in `/etc/ly/config.ini`. The file is commented, and includes the default values. ## Controls Use the up and down arrow keys to change the current field, and the left and right arrow keys to change the target desktop environment while on the desktop field (above the login field). ## .xinitrc If your .xinitrc doesn't work make sure it is executable and includes a shebang. This file is supposed to be a shell script! Quoting from xinit's man page: > If no specific client program is given on the command line, xinit will look for a file in the user's home directory called .xinitrc to run as a shell script to start up client programs. On Arch Linux, the example .xinitrc (/etc/X11/xinit/xinitrc) starts like this: ``` #!/bin/sh ``` ## Tips The numlock and capslock state is printed in the top-right corner. Use the F1 and F2 keys to respectively shutdown and reboot. Take a look at your .xsession if X doesn't start, as it can interfere (this file is launched with X to configure the display properly). ## PSX DOOM fire animation To enable the famous PSX DOOM fire described by [Fabien Sanglard](http://fabiensanglard.net/doom_fire_psx/index.html), just set `animation = doom` in `/etc/ly/config.ini`. You may also disable the main box borders with `hide_borders = true`. ## Additional Information The name "Ly" is a tribute to the fairy from the game Rayman. Ly was tested by oxodao, who is some seriously awesome dude.
0
repos/ly
repos/ly/include/termbox2.h
/* MIT License Copyright (c) 2010-2020 nsf <[email protected]> 2015-2024 Adam Saponara <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TERMBOX_H_INCL #define TERMBOX_H_INCL #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE #endif #ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE #endif #include <errno.h> #include <fcntl.h> #include <limits.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <wchar.h> #ifdef PATH_MAX #define TB_PATH_MAX PATH_MAX #else #define TB_PATH_MAX 4096 #endif #ifdef __cplusplus extern "C" { #endif // __ffi_start #define TB_VERSION_STR "2.5.0-dev" /* The following compile-time options are supported: * * TB_OPT_ATTR_W: Integer width of fg and bg attributes. Valid values * (assuming system support) are 16, 32, and 64. (See * uintattr_t). 32 or 64 enables output mode * TB_OUTPUT_TRUECOLOR. 64 enables additional style * attributes. (See tb_set_output_mode.) Larger values * consume more memory in exchange for more features. * Defaults to 16. * * TB_OPT_EGC: If set, enable extended grapheme cluster support * (tb_extend_cell, tb_set_cell_ex). Consumes more memory. * Defaults off. * * TB_OPT_PRINTF_BUF: Write buffer size for printf operations. Represents the * largest string that can be sent in one call to tb_print* * and tb_send* functions. Defaults to 4096. * * TB_OPT_READ_BUF: Read buffer size for tty reads. Defaults to 64. * * TB_OPT_TRUECOLOR: Deprecated. Sets TB_OPT_ATTR_W to 32 if not already set. */ #if defined(TB_LIB_OPTS) || 0 // __tb_lib_opts // Ensure consistent compile-time options when using as a shared library #undef TB_OPT_ATTR_W #undef TB_OPT_EGC #undef TB_OPT_PRINTF_BUF #undef TB_OPT_READ_BUF #define TB_OPT_ATTR_W 64 #define TB_OPT_EGC #endif // Ensure sane TB_OPT_ATTR_W (16, 32, or 64) #if defined TB_OPT_ATTR_W && TB_OPT_ATTR_W == 16 #elif defined TB_OPT_ATTR_W && TB_OPT_ATTR_W == 32 #elif defined TB_OPT_ATTR_W && TB_OPT_ATTR_W == 64 #else #undef TB_OPT_ATTR_W #if defined TB_OPT_TRUECOLOR // Deprecated. Back-compat for old flag. #define TB_OPT_ATTR_W 32 #else #define TB_OPT_ATTR_W 16 #endif #endif /* ASCII key constants (tb_event.key) */ #define TB_KEY_CTRL_TILDE 0x00 #define TB_KEY_CTRL_2 0x00 /* clash with 'CTRL_TILDE' */ #define TB_KEY_CTRL_A 0x01 #define TB_KEY_CTRL_B 0x02 #define TB_KEY_CTRL_C 0x03 #define TB_KEY_CTRL_D 0x04 #define TB_KEY_CTRL_E 0x05 #define TB_KEY_CTRL_F 0x06 #define TB_KEY_CTRL_G 0x07 #define TB_KEY_BACKSPACE 0x08 #define TB_KEY_CTRL_H 0x08 /* clash with 'CTRL_BACKSPACE' */ #define TB_KEY_TAB 0x09 #define TB_KEY_CTRL_I 0x09 /* clash with 'TAB' */ #define TB_KEY_CTRL_J 0x0a #define TB_KEY_CTRL_K 0x0b #define TB_KEY_CTRL_L 0x0c #define TB_KEY_ENTER 0x0d #define TB_KEY_CTRL_M 0x0d /* clash with 'ENTER' */ #define TB_KEY_CTRL_N 0x0e #define TB_KEY_CTRL_O 0x0f #define TB_KEY_CTRL_P 0x10 #define TB_KEY_CTRL_Q 0x11 #define TB_KEY_CTRL_R 0x12 #define TB_KEY_CTRL_S 0x13 #define TB_KEY_CTRL_T 0x14 #define TB_KEY_CTRL_U 0x15 #define TB_KEY_CTRL_V 0x16 #define TB_KEY_CTRL_W 0x17 #define TB_KEY_CTRL_X 0x18 #define TB_KEY_CTRL_Y 0x19 #define TB_KEY_CTRL_Z 0x1a #define TB_KEY_ESC 0x1b #define TB_KEY_CTRL_LSQ_BRACKET 0x1b /* clash with 'ESC' */ #define TB_KEY_CTRL_3 0x1b /* clash with 'ESC' */ #define TB_KEY_CTRL_4 0x1c #define TB_KEY_CTRL_BACKSLASH 0x1c /* clash with 'CTRL_4' */ #define TB_KEY_CTRL_5 0x1d #define TB_KEY_CTRL_RSQ_BRACKET 0x1d /* clash with 'CTRL_5' */ #define TB_KEY_CTRL_6 0x1e #define TB_KEY_CTRL_7 0x1f #define TB_KEY_CTRL_SLASH 0x1f /* clash with 'CTRL_7' */ #define TB_KEY_CTRL_UNDERSCORE 0x1f /* clash with 'CTRL_7' */ #define TB_KEY_SPACE 0x20 #define TB_KEY_BACKSPACE2 0x7f #define TB_KEY_CTRL_8 0x7f /* clash with 'BACKSPACE2' */ #define tb_key_i(i) 0xffff - (i) /* Terminal-dependent key constants (tb_event.key) and terminfo capabilities */ /* BEGIN codegen h */ /* Produced by ./codegen.sh on Thu, 13 Jul 2023 05:46:13 +0000 */ #define TB_KEY_F1 (0xffff - 0) #define TB_KEY_F2 (0xffff - 1) #define TB_KEY_F3 (0xffff - 2) #define TB_KEY_F4 (0xffff - 3) #define TB_KEY_F5 (0xffff - 4) #define TB_KEY_F6 (0xffff - 5) #define TB_KEY_F7 (0xffff - 6) #define TB_KEY_F8 (0xffff - 7) #define TB_KEY_F9 (0xffff - 8) #define TB_KEY_F10 (0xffff - 9) #define TB_KEY_F11 (0xffff - 10) #define TB_KEY_F12 (0xffff - 11) #define TB_KEY_INSERT (0xffff - 12) #define TB_KEY_DELETE (0xffff - 13) #define TB_KEY_HOME (0xffff - 14) #define TB_KEY_END (0xffff - 15) #define TB_KEY_PGUP (0xffff - 16) #define TB_KEY_PGDN (0xffff - 17) #define TB_KEY_ARROW_UP (0xffff - 18) #define TB_KEY_ARROW_DOWN (0xffff - 19) #define TB_KEY_ARROW_LEFT (0xffff - 20) #define TB_KEY_ARROW_RIGHT (0xffff - 21) #define TB_KEY_BACK_TAB (0xffff - 22) #define TB_KEY_MOUSE_LEFT (0xffff - 23) #define TB_KEY_MOUSE_RIGHT (0xffff - 24) #define TB_KEY_MOUSE_MIDDLE (0xffff - 25) #define TB_KEY_MOUSE_RELEASE (0xffff - 26) #define TB_KEY_MOUSE_WHEEL_UP (0xffff - 27) #define TB_KEY_MOUSE_WHEEL_DOWN (0xffff - 28) #define TB_CAP_F1 0 #define TB_CAP_F2 1 #define TB_CAP_F3 2 #define TB_CAP_F4 3 #define TB_CAP_F5 4 #define TB_CAP_F6 5 #define TB_CAP_F7 6 #define TB_CAP_F8 7 #define TB_CAP_F9 8 #define TB_CAP_F10 9 #define TB_CAP_F11 10 #define TB_CAP_F12 11 #define TB_CAP_INSERT 12 #define TB_CAP_DELETE 13 #define TB_CAP_HOME 14 #define TB_CAP_END 15 #define TB_CAP_PGUP 16 #define TB_CAP_PGDN 17 #define TB_CAP_ARROW_UP 18 #define TB_CAP_ARROW_DOWN 19 #define TB_CAP_ARROW_LEFT 20 #define TB_CAP_ARROW_RIGHT 21 #define TB_CAP_BACK_TAB 22 #define TB_CAP__COUNT_KEYS 23 #define TB_CAP_ENTER_CA 23 #define TB_CAP_EXIT_CA 24 #define TB_CAP_SHOW_CURSOR 25 #define TB_CAP_HIDE_CURSOR 26 #define TB_CAP_CLEAR_SCREEN 27 #define TB_CAP_SGR0 28 #define TB_CAP_UNDERLINE 29 #define TB_CAP_BOLD 30 #define TB_CAP_BLINK 31 #define TB_CAP_ITALIC 32 #define TB_CAP_REVERSE 33 #define TB_CAP_ENTER_KEYPAD 34 #define TB_CAP_EXIT_KEYPAD 35 #define TB_CAP_DIM 36 #define TB_CAP_INVISIBLE 37 #define TB_CAP__COUNT 38 /* END codegen h */ /* Some hard-coded caps */ #define TB_HARDCAP_ENTER_MOUSE "\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h" #define TB_HARDCAP_EXIT_MOUSE "\x1b[?1006l\x1b[?1015l\x1b[?1002l\x1b[?1000l" #define TB_HARDCAP_STRIKEOUT "\x1b[9m" #define TB_HARDCAP_UNDERLINE_2 "\x1b[21m" #define TB_HARDCAP_OVERLINE "\x1b[53m" /* Colors (numeric) and attributes (bitwise) (tb_cell.fg, tb_cell.bg) */ #define TB_DEFAULT 0x0000 #define TB_BLACK 0x0001 #define TB_RED 0x0002 #define TB_GREEN 0x0003 #define TB_YELLOW 0x0004 #define TB_BLUE 0x0005 #define TB_MAGENTA 0x0006 #define TB_CYAN 0x0007 #define TB_WHITE 0x0008 #if TB_OPT_ATTR_W == 16 #define TB_BOLD 0x0100 #define TB_UNDERLINE 0x0200 #define TB_REVERSE 0x0400 #define TB_ITALIC 0x0800 #define TB_BLINK 0x1000 #define TB_HI_BLACK 0x2000 #define TB_BRIGHT 0x4000 #define TB_DIM 0x8000 #define TB_256_BLACK TB_HI_BLACK // TB_256_BLACK is deprecated #else // 32 or 64 #define TB_BOLD 0x01000000 #define TB_UNDERLINE 0x02000000 #define TB_REVERSE 0x04000000 #define TB_ITALIC 0x08000000 #define TB_BLINK 0x10000000 #define TB_HI_BLACK 0x20000000 #define TB_BRIGHT 0x40000000 #define TB_DIM 0x80000000 #define TB_TRUECOLOR_BOLD TB_BOLD // TB_TRUECOLOR_* is deprecated #define TB_TRUECOLOR_UNDERLINE TB_UNDERLINE #define TB_TRUECOLOR_REVERSE TB_REVERSE #define TB_TRUECOLOR_ITALIC TB_ITALIC #define TB_TRUECOLOR_BLINK TB_BLINK #define TB_TRUECOLOR_BLACK TB_HI_BLACK #endif #if TB_OPT_ATTR_W == 64 #define TB_STRIKEOUT 0x0000000100000000 #define TB_UNDERLINE_2 0x0000000200000000 #define TB_OVERLINE 0x0000000400000000 #define TB_INVISIBLE 0x0000000800000000 #endif /* Event types (tb_event.type) */ #define TB_EVENT_KEY 1 #define TB_EVENT_RESIZE 2 #define TB_EVENT_MOUSE 3 /* Key modifiers (bitwise) (tb_event.mod) */ #define TB_MOD_ALT 1 #define TB_MOD_CTRL 2 #define TB_MOD_SHIFT 4 #define TB_MOD_MOTION 8 /* Input modes (bitwise) (tb_set_input_mode) */ #define TB_INPUT_CURRENT 0 #define TB_INPUT_ESC 1 #define TB_INPUT_ALT 2 #define TB_INPUT_MOUSE 4 /* Output modes (tb_set_output_mode) */ #define TB_OUTPUT_CURRENT 0 #define TB_OUTPUT_NORMAL 1 #define TB_OUTPUT_256 2 #define TB_OUTPUT_216 3 #define TB_OUTPUT_GRAYSCALE 4 #if TB_OPT_ATTR_W >= 32 #define TB_OUTPUT_TRUECOLOR 5 #endif /* Common function return values unless otherwise noted. * * Library behavior is undefined after receiving TB_ERR_MEM. Callers may * attempt reinitializing by freeing memory, invoking tb_shutdown, then * tb_init. */ #define TB_OK 0 #define TB_ERR -1 #define TB_ERR_NEED_MORE -2 #define TB_ERR_INIT_ALREADY -3 #define TB_ERR_INIT_OPEN -4 #define TB_ERR_MEM -5 #define TB_ERR_NO_EVENT -6 #define TB_ERR_NO_TERM -7 #define TB_ERR_NOT_INIT -8 #define TB_ERR_OUT_OF_BOUNDS -9 #define TB_ERR_READ -10 #define TB_ERR_RESIZE_IOCTL -11 #define TB_ERR_RESIZE_PIPE -12 #define TB_ERR_RESIZE_SIGACTION -13 #define TB_ERR_POLL -14 #define TB_ERR_TCGETATTR -15 #define TB_ERR_TCSETATTR -16 #define TB_ERR_UNSUPPORTED_TERM -17 #define TB_ERR_RESIZE_WRITE -18 #define TB_ERR_RESIZE_POLL -19 #define TB_ERR_RESIZE_READ -20 #define TB_ERR_RESIZE_SSCANF -21 #define TB_ERR_CAP_COLLISION -22 #define TB_ERR_SELECT TB_ERR_POLL #define TB_ERR_RESIZE_SELECT TB_ERR_RESIZE_POLL /* Deprecated. Function types to be used with tb_set_func(). */ #define TB_FUNC_EXTRACT_PRE 0 #define TB_FUNC_EXTRACT_POST 1 /* Define this to set the size of the buffer used in tb_printf() * and tb_sendf() */ #ifndef TB_OPT_PRINTF_BUF #define TB_OPT_PRINTF_BUF 4096 #endif /* Define this to set the size of the read buffer used when reading * from the tty */ #ifndef TB_OPT_READ_BUF #define TB_OPT_READ_BUF 64 #endif /* Define this for limited back compat with termbox v1 */ #ifdef TB_OPT_V1_COMPAT #define tb_change_cell tb_set_cell #define tb_put_cell(x, y, c) tb_set_cell((x), (y), (c)->ch, (c)->fg, (c)->bg) #define tb_set_clear_attributes tb_set_clear_attrs #define tb_select_input_mode tb_set_input_mode #define tb_select_output_mode tb_set_output_mode #endif /* Define these to swap in a different allocator */ #ifndef tb_malloc #define tb_malloc malloc #define tb_realloc realloc #define tb_free free #endif #if TB_OPT_ATTR_W == 64 typedef uint64_t uintattr_t; #elif TB_OPT_ATTR_W == 32 typedef uint32_t uintattr_t; #else // 16 typedef uint16_t uintattr_t; #endif /* The terminal screen is represented as 2d array of cells. The structure is * optimized for dealing with single-width (wcwidth()==1) Unicode codepoints, * however some support for grapheme clusters (e.g., combining diacritical * marks) and wide codepoints (e.g., Hiragana) is provided through ech, nech, * cech via tb_set_cell_ex(). ech is only valid when nech>0, otherwise ch is * used. * * For non-single-width codepoints, given N=wcwidth(ch)/wcswidth(ech): * * when N==0: termbox forces a single-width cell. Callers should avoid this * if aiming to render text accurately. * * when N>1: termbox zeroes out the following N-1 cells and skips sending * them to the tty. So, e.g., if the caller sets x=0,y=0 to an N==2 * codepoint, the caller's next set should be at x=2,y=0. Anything * set at x=1,y=0 will be ignored. If there are not enough columns * remaining on the line to render N width, spaces are sent * instead. * * See tb_present() for implementation. */ struct tb_cell { uint32_t ch; /* a Unicode codepoint */ uintattr_t fg; /* bitwise foreground attributes */ uintattr_t bg; /* bitwise background attributes */ #ifdef TB_OPT_EGC uint32_t *ech; /* a grapheme cluster of Unicode codepoints, 0-terminated */ size_t nech; /* num elements in ech, 0 means use ch instead of ech */ size_t cech; /* num elements allocated for ech */ #endif }; /* An incoming event from the tty. * * Given the event type, the following fields are relevant: * * when TB_EVENT_KEY: (key XOR ch, one will be zero), mod. Note there is * overlap between TB_MOD_CTRL and TB_KEY_CTRL_*. * TB_MOD_CTRL and TB_MOD_SHIFT are only set as * modifiers to TB_KEY_ARROW_*. * * when TB_EVENT_RESIZE: w, h * * when TB_EVENT_MOUSE: key (TB_KEY_MOUSE_*), x, y */ struct tb_event { uint8_t type; /* one of TB_EVENT_* constants */ uint8_t mod; /* bitwise TB_MOD_* constants */ uint16_t key; /* one of TB_KEY_* constants */ uint32_t ch; /* a Unicode codepoint */ int32_t w; /* resize width */ int32_t h; /* resize height */ int32_t x; /* mouse x */ int32_t y; /* mouse y */ }; /* Initializes the termbox library. This function should be called before any * other functions. tb_init() is equivalent to tb_init_file("/dev/tty"). After * successful initialization, the library must be finalized using the * tb_shutdown() function. */ int tb_init(void); int tb_init_file(const char *path); int tb_init_fd(int ttyfd); int tb_init_rwfd(int rfd, int wfd); int tb_shutdown(void); /* Returns the size of the internal back buffer (which is the same as terminal's * window size in rows and columns). The internal buffer can be resized after * tb_clear() or tb_present() function calls. Both dimensions have an * unspecified negative value when called before tb_init() or after * tb_shutdown(). */ int tb_width(void); int tb_height(void); /* Clears the internal back buffer using TB_DEFAULT color or the * color/attributes set by tb_set_clear_attrs() function. */ int tb_clear(void); int tb_set_clear_attrs(uintattr_t fg, uintattr_t bg); /* Synchronizes the internal back buffer with the terminal by writing to tty. */ int tb_present(void); /* Clears the internal front buffer effectively forcing a complete re-render of * the back buffer to the tty. It is not necessary to call this under normal * circumstances. */ int tb_invalidate(void); /* Sets the position of the cursor. Upper-left character is (0, 0). */ int tb_set_cursor(int cx, int cy); int tb_hide_cursor(void); /* Set cell contents in the internal back buffer at the specified position. * * Use tb_set_cell_ex() for rendering grapheme clusters (e.g., combining * diacritical marks). * * Function tb_set_cell(x, y, ch, fg, bg) is equivalent to * tb_set_cell_ex(x, y, &ch, 1, fg, bg). * * Function tb_extend_cell() is a shortcut for appending 1 codepoint to * cell->ech. */ int tb_set_cell(int x, int y, uint32_t ch, uintattr_t fg, uintattr_t bg); int tb_set_cell_ex(int x, int y, uint32_t *ch, size_t nch, uintattr_t fg, uintattr_t bg); int tb_extend_cell(int x, int y, uint32_t ch); /* Sets the input mode. Termbox has two input modes: * * 1. TB_INPUT_ESC * When escape (\x1b) is in the buffer and there's no match for an escape * sequence, a key event for TB_KEY_ESC is returned. * * 2. TB_INPUT_ALT * When escape (\x1b) is in the buffer and there's no match for an escape * sequence, the next keyboard event is returned with a TB_MOD_ALT modifier. * * You can also apply TB_INPUT_MOUSE via bitwise OR operation to either of the * modes (e.g., TB_INPUT_ESC | TB_INPUT_MOUSE) to receive TB_EVENT_MOUSE events. * If none of the main two modes were set, but the mouse mode was, TB_INPUT_ESC * mode is used. If for some reason you've decided to use * (TB_INPUT_ESC | TB_INPUT_ALT) combination, it will behave as if only * TB_INPUT_ESC was selected. * * If mode is TB_INPUT_CURRENT, the function returns the current input mode. * * The default input mode is TB_INPUT_ESC. */ int tb_set_input_mode(int mode); /* Sets the termbox output mode. Termbox has multiple output modes: * * 1. TB_OUTPUT_NORMAL => [0..8] * * This mode provides 8 different colors: * TB_BLACK, TB_RED, TB_GREEN, TB_YELLOW, * TB_BLUE, TB_MAGENTA, TB_CYAN, TB_WHITE * * Plus TB_DEFAULT which skips sending a color code (i.e., uses the * terminal's default color). * * Colors (including TB_DEFAULT) may be bitwise OR'd with attributes: * TB_BOLD, TB_UNDERLINE, TB_REVERSE, TB_ITALIC, TB_BLINK, TB_BRIGHT, * TB_DIM * * The following style attributes are also available if compiled with * TB_OPT_ATTR_W set to 64: * TB_STRIKEOUT, TB_UNDERLINE_2, TB_OVERLINE, TB_INVISIBLE * * As in all modes, the value 0 is interpreted as TB_DEFAULT for * convenience. * * Some notes: TB_REVERSE can be applied as either fg or bg attributes for * the same effect. TB_BRIGHT can be applied to either fg or bg. The rest of * the attributes apply to fg only and are ignored as bg attributes. * * Example usage: * tb_set_cell(x, y, '@', TB_BLACK | TB_BOLD, TB_RED); * * 2. TB_OUTPUT_256 => [0..255] + TB_HI_BLACK * * In this mode you get 256 distinct colors (plus default): * 0x00 (1): TB_DEFAULT * TB_HI_BLACK (1): TB_BLACK in TB_OUTPUT_NORMAL * 0x01..0x07 (7): the next 7 colors as in TB_OUTPUT_NORMAL * 0x08..0x0f (8): bright versions of the above * 0x10..0xe7 (216): 216 different colors * 0xe8..0xff (24): 24 different shades of gray * * All TB_* style attributes except TB_BRIGHT may be bitwise OR'd as in * TB_OUTPUT_NORMAL. * * Note TB_HI_BLACK must be used for black, as 0x00 represents default. * * 3. TB_OUTPUT_216 => [0..216] * * This mode supports the 216-color range of TB_OUTPUT_256 only, but you * don't need to provide an offset: * 0x00 (1): TB_DEFAULT * 0x01..0xd8 (216): 216 different colors * * 4. TB_OUTPUT_GRAYSCALE => [0..24] * * This mode supports the 24-color range of TB_OUTPUT_256 only, but you * don't need to provide an offset: * 0x00 (1): TB_DEFAULT * 0x01..0x18 (24): 24 different shades of gray * * 5. TB_OUTPUT_TRUECOLOR => [0x000000..0xffffff] + TB_HI_BLACK * * This mode provides 24-bit color on supported terminals. The format is * 0xRRGGBB. * * All TB_* style attributes except TB_BRIGHT may be bitwise OR'd as in * TB_OUTPUT_NORMAL. * * Note TB_HI_BLACK must be used for black, as 0x000000 represents default. * * If mode is TB_OUTPUT_CURRENT, the function returns the current output mode. * * The default output mode is TB_OUTPUT_NORMAL. * * To use the terminal default color (i.e., to not send an escape code), pass * TB_DEFAULT. For convenience, the value 0 is interpreted as TB_DEFAULT in * all modes. * * Note, cell attributes persist after switching output modes. Any translation * between, for example, TB_OUTPUT_NORMAL's TB_RED and TB_OUTPUT_TRUECOLOR's * 0xff0000 must be performed by the caller. Also note that cells previously * rendered in one mode may persist unchanged until the front buffer is cleared * (such as after a resize event) at which point it will be re-interpreted and * flushed according to the current mode. Callers may invoke tb_invalidate if * it is desirable to immediately re-interpret and flush the entire screen * according to the current mode. * * Note, not all terminals support all output modes, especially beyond * TB_OUTPUT_NORMAL. There is also no very reliable way to determine color * support dynamically. If portability is desired, callers are recommended to * use TB_OUTPUT_NORMAL or make output mode end-user configurable. The same * advice applies to style attributes. */ int tb_set_output_mode(int mode); /* Wait for an event up to timeout_ms milliseconds and fill the event structure * with it. If no event is available within the timeout period, TB_ERR_NO_EVENT * is returned. On a resize event, the underlying select(2) call may be * interrupted, yielding a return code of TB_ERR_POLL. In this case, you may * check errno via tb_last_errno(). If it's EINTR, you can safely ignore that * and call tb_peek_event() again. */ int tb_peek_event(struct tb_event *event, int timeout_ms); /* Same as tb_peek_event except no timeout. */ int tb_poll_event(struct tb_event *event); /* Internal termbox FDs that can be used with poll() / select(). Must call * tb_poll_event() / tb_peek_event() if activity is detected. */ int tb_get_fds(int *ttyfd, int *resizefd); /* Print and printf functions. Specify param out_w to determine width of printed * string. Incomplete trailing UTF-8 byte sequences are replaced with U+FFFD. * For finer control, use tb_set_cell(). */ int tb_print(int x, int y, uintattr_t fg, uintattr_t bg, const char *str); int tb_printf(int x, int y, uintattr_t fg, uintattr_t bg, const char *fmt, ...); int tb_print_ex(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *str); int tb_printf_ex(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *fmt, ...); /* Send raw bytes to terminal. */ int tb_send(const char *buf, size_t nbuf); int tb_sendf(const char *fmt, ...); /* Deprecated. Set custom functions. fn_type is one of TB_FUNC_* constants, fn * is a compatible function pointer, or NULL to clear. * * TB_FUNC_EXTRACT_PRE: * If specified, invoke this function BEFORE termbox tries to extract any * escape sequences from the input buffer. * * TB_FUNC_EXTRACT_POST: * If specified, invoke this function AFTER termbox tries (and fails) to * extract any escape sequences from the input buffer. */ int tb_set_func(int fn_type, int (*fn)(struct tb_event *, size_t *)); /* Return byte length of codepoint given first byte of UTF-8 sequence (1-6). */ int tb_utf8_char_length(char c); /* Convert UTF-8 null-terminated byte sequence to UTF-32 codepoint. * * If `c` is an empty C string, return 0. `out` is left unchanged. * * If a null byte is encountered in the middle of the codepoint, return a * negative number indicating how many bytes were processed. `out` is left * unchanged. * * Otherwise, return byte length of codepoint (1-6). */ int tb_utf8_char_to_unicode(uint32_t *out, const char *c); /* Convert UTF-32 codepoint to UTF-8 null-terminated byte sequence. * * `out` must be char[7] or greater. Return byte length of codepoint (1-6). */ int tb_utf8_unicode_to_char(char *out, uint32_t c); /* Library utility functions */ int tb_last_errno(void); const char *tb_strerror(int err); struct tb_cell *tb_cell_buffer(void); // Deprecated int tb_has_truecolor(void); int tb_has_egc(void); int tb_attr_width(void); const char *tb_version(void); /* Deprecation notice! * * The following will be removed in version 3.x (ABI version 3): * * TB_256_BLACK (use TB_HI_BLACK) * TB_OPT_TRUECOLOR (use TB_OPT_ATTR_W) * TB_TRUECOLOR_BOLD (use TB_BOLD) * TB_TRUECOLOR_UNDERLINE (use TB_UNDERLINE) * TB_TRUECOLOR_REVERSE (use TB_REVERSE) * TB_TRUECOLOR_ITALIC (use TB_ITALICe) * TB_TRUECOLOR_BLINK (use TB_BLINK) * TB_TRUECOLOR_BLACK (use TB_HI_BLACK) * tb_cell_buffer * tb_set_func * TB_FUNC_EXTRACT_PRE * TB_FUNC_EXTRACT_POST */ #ifdef __cplusplus } #endif #endif /* TERMBOX_H_INCL */ #ifdef TB_IMPL #define if_err_return(rv, expr) \ if (((rv) = (expr)) != TB_OK) return (rv) #define if_err_break(rv, expr) \ if (((rv) = (expr)) != TB_OK) break #define if_ok_return(rv, expr) \ if (((rv) = (expr)) == TB_OK) return (rv) #define if_ok_or_need_more_return(rv, expr) \ if (((rv) = (expr)) == TB_OK || (rv) == TB_ERR_NEED_MORE) return (rv) #define send_literal(rv, a) \ if_err_return((rv), bytebuf_nputs(&global.out, (a), sizeof(a) - 1)) #define send_num(rv, nbuf, n) \ if_err_return((rv), \ bytebuf_nputs(&global.out, (nbuf), convert_num((n), (nbuf)))) #define snprintf_or_return(rv, str, sz, fmt, ...) \ do { \ (rv) = snprintf((str), (sz), (fmt), __VA_ARGS__); \ if ((rv) < 0 || (rv) >= (int)(sz)) return TB_ERR; \ } while (0) #define if_not_init_return() \ if (!global.initialized) return TB_ERR_NOT_INIT struct bytebuf_t { char *buf; size_t len; size_t cap; }; struct cellbuf_t { int width; int height; struct tb_cell *cells; }; struct cap_trie_t { char c; struct cap_trie_t *children; size_t nchildren; int is_leaf; uint16_t key; uint8_t mod; }; struct tb_global_t { int ttyfd; int rfd; int wfd; int ttyfd_open; int resize_pipefd[2]; int width; int height; int cursor_x; int cursor_y; int last_x; int last_y; uintattr_t fg; uintattr_t bg; uintattr_t last_fg; uintattr_t last_bg; int input_mode; int output_mode; char *terminfo; size_t nterminfo; const char *caps[TB_CAP__COUNT]; struct cap_trie_t cap_trie; struct bytebuf_t in; struct bytebuf_t out; struct cellbuf_t back; struct cellbuf_t front; struct termios orig_tios; int has_orig_tios; int last_errno; int initialized; int (*fn_extract_esc_pre)(struct tb_event *, size_t *); int (*fn_extract_esc_post)(struct tb_event *, size_t *); char errbuf[1024]; }; static struct tb_global_t global = {0}; /* BEGIN codegen c */ /* Produced by ./codegen.sh on Thu, 13 Jul 2023 05:46:13 +0000 */ static const int16_t terminfo_cap_indexes[] = { 66, // kf1 (TB_CAP_F1) 68, // kf2 (TB_CAP_F2) 69, // kf3 (TB_CAP_F3) 70, // kf4 (TB_CAP_F4) 71, // kf5 (TB_CAP_F5) 72, // kf6 (TB_CAP_F6) 73, // kf7 (TB_CAP_F7) 74, // kf8 (TB_CAP_F8) 75, // kf9 (TB_CAP_F9) 67, // kf10 (TB_CAP_F10) 216, // kf11 (TB_CAP_F11) 217, // kf12 (TB_CAP_F12) 77, // kich1 (TB_CAP_INSERT) 59, // kdch1 (TB_CAP_DELETE) 76, // khome (TB_CAP_HOME) 164, // kend (TB_CAP_END) 82, // kpp (TB_CAP_PGUP) 81, // knp (TB_CAP_PGDN) 87, // kcuu1 (TB_CAP_ARROW_UP) 61, // kcud1 (TB_CAP_ARROW_DOWN) 79, // kcub1 (TB_CAP_ARROW_LEFT) 83, // kcuf1 (TB_CAP_ARROW_RIGHT) 148, // kcbt (TB_CAP_BACK_TAB) 28, // smcup (TB_CAP_ENTER_CA) 40, // rmcup (TB_CAP_EXIT_CA) 16, // cnorm (TB_CAP_SHOW_CURSOR) 13, // civis (TB_CAP_HIDE_CURSOR) 5, // clear (TB_CAP_CLEAR_SCREEN) 39, // sgr0 (TB_CAP_SGR0) 36, // smul (TB_CAP_UNDERLINE) 27, // bold (TB_CAP_BOLD) 26, // blink (TB_CAP_BLINK) 311, // sitm (TB_CAP_ITALIC) 34, // rev (TB_CAP_REVERSE) 89, // smkx (TB_CAP_ENTER_KEYPAD) 88, // rmkx (TB_CAP_EXIT_KEYPAD) 30, // dim (TB_CAP_DIM) 32, // invis (TB_CAP_INVISIBLE) }; // xterm static const char *xterm_caps[] = { "\033OP", // kf1 (TB_CAP_F1) "\033OQ", // kf2 (TB_CAP_F2) "\033OR", // kf3 (TB_CAP_F3) "\033OS", // kf4 (TB_CAP_F4) "\033[15~", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033OH", // khome (TB_CAP_HOME) "\033OF", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033OA", // kcuu1 (TB_CAP_ARROW_UP) "\033OB", // kcud1 (TB_CAP_ARROW_DOWN) "\033OD", // kcub1 (TB_CAP_ARROW_LEFT) "\033OC", // kcuf1 (TB_CAP_ARROW_RIGHT) "\033[Z", // kcbt (TB_CAP_BACK_TAB) "\033[?1049h\033[22;0;0t", // smcup (TB_CAP_ENTER_CA) "\033[?1049l\033[23;0;0t", // rmcup (TB_CAP_EXIT_CA) "\033[?12l\033[?25h", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[2J", // clear (TB_CAP_CLEAR_SCREEN) "\033(B\033[m", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "\033[3m", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "\033[?1h\033=", // smkx (TB_CAP_ENTER_KEYPAD) "\033[?1l\033>", // rmkx (TB_CAP_EXIT_KEYPAD) "\033[2m", // dim (TB_CAP_DIM) "\033[8m", // invis (TB_CAP_INVISIBLE) }; // linux static const char *linux_caps[] = { "\033[[A", // kf1 (TB_CAP_F1) "\033[[B", // kf2 (TB_CAP_F2) "\033[[C", // kf3 (TB_CAP_F3) "\033[[D", // kf4 (TB_CAP_F4) "\033[[E", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033[1~", // khome (TB_CAP_HOME) "\033[4~", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033[A", // kcuu1 (TB_CAP_ARROW_UP) "\033[B", // kcud1 (TB_CAP_ARROW_DOWN) "\033[D", // kcub1 (TB_CAP_ARROW_LEFT) "\033[C", // kcuf1 (TB_CAP_ARROW_RIGHT) "\033\011", // kcbt (TB_CAP_BACK_TAB) "", // smcup (TB_CAP_ENTER_CA) "", // rmcup (TB_CAP_EXIT_CA) "\033[?25h\033[?0c", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l\033[?1c", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[J", // clear (TB_CAP_CLEAR_SCREEN) "\033[m\017", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "", // smkx (TB_CAP_ENTER_KEYPAD) "", // rmkx (TB_CAP_EXIT_KEYPAD) "\033[2m", // dim (TB_CAP_DIM) "", // invis (TB_CAP_INVISIBLE) }; // screen static const char *screen_caps[] = { "\033OP", // kf1 (TB_CAP_F1) "\033OQ", // kf2 (TB_CAP_F2) "\033OR", // kf3 (TB_CAP_F3) "\033OS", // kf4 (TB_CAP_F4) "\033[15~", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033[1~", // khome (TB_CAP_HOME) "\033[4~", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033OA", // kcuu1 (TB_CAP_ARROW_UP) "\033OB", // kcud1 (TB_CAP_ARROW_DOWN) "\033OD", // kcub1 (TB_CAP_ARROW_LEFT) "\033OC", // kcuf1 (TB_CAP_ARROW_RIGHT) "\033[Z", // kcbt (TB_CAP_BACK_TAB) "\033[?1049h", // smcup (TB_CAP_ENTER_CA) "\033[?1049l", // rmcup (TB_CAP_EXIT_CA) "\033[34h\033[?25h", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[J", // clear (TB_CAP_CLEAR_SCREEN) "\033[m\017", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "\033[?1h\033=", // smkx (TB_CAP_ENTER_KEYPAD) "\033[?1l\033>", // rmkx (TB_CAP_EXIT_KEYPAD) "\033[2m", // dim (TB_CAP_DIM) "", // invis (TB_CAP_INVISIBLE) }; // rxvt-256color static const char *rxvt_256color_caps[] = { "\033[11~", // kf1 (TB_CAP_F1) "\033[12~", // kf2 (TB_CAP_F2) "\033[13~", // kf3 (TB_CAP_F3) "\033[14~", // kf4 (TB_CAP_F4) "\033[15~", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033[7~", // khome (TB_CAP_HOME) "\033[8~", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033[A", // kcuu1 (TB_CAP_ARROW_UP) "\033[B", // kcud1 (TB_CAP_ARROW_DOWN) "\033[D", // kcub1 (TB_CAP_ARROW_LEFT) "\033[C", // kcuf1 (TB_CAP_ARROW_RIGHT) "\033[Z", // kcbt (TB_CAP_BACK_TAB) "\0337\033[?47h", // smcup (TB_CAP_ENTER_CA) "\033[2J\033[?47l\0338", // rmcup (TB_CAP_EXIT_CA) "\033[?25h", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[2J", // clear (TB_CAP_CLEAR_SCREEN) "\033[m\017", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "\033=", // smkx (TB_CAP_ENTER_KEYPAD) "\033>", // rmkx (TB_CAP_EXIT_KEYPAD) "", // dim (TB_CAP_DIM) "", // invis (TB_CAP_INVISIBLE) }; // rxvt-unicode static const char *rxvt_unicode_caps[] = { "\033[11~", // kf1 (TB_CAP_F1) "\033[12~", // kf2 (TB_CAP_F2) "\033[13~", // kf3 (TB_CAP_F3) "\033[14~", // kf4 (TB_CAP_F4) "\033[15~", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033[7~", // khome (TB_CAP_HOME) "\033[8~", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033[A", // kcuu1 (TB_CAP_ARROW_UP) "\033[B", // kcud1 (TB_CAP_ARROW_DOWN) "\033[D", // kcub1 (TB_CAP_ARROW_LEFT) "\033[C", // kcuf1 (TB_CAP_ARROW_RIGHT) "\033[Z", // kcbt (TB_CAP_BACK_TAB) "\033[?1049h", // smcup (TB_CAP_ENTER_CA) "\033[r\033[?1049l", // rmcup (TB_CAP_EXIT_CA) "\033[?12l\033[?25h", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[2J", // clear (TB_CAP_CLEAR_SCREEN) "\033[m\033(B", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "\033[3m", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "\033=", // smkx (TB_CAP_ENTER_KEYPAD) "\033>", // rmkx (TB_CAP_EXIT_KEYPAD) "", // dim (TB_CAP_DIM) "", // invis (TB_CAP_INVISIBLE) }; // Eterm static const char *eterm_caps[] = { "\033[11~", // kf1 (TB_CAP_F1) "\033[12~", // kf2 (TB_CAP_F2) "\033[13~", // kf3 (TB_CAP_F3) "\033[14~", // kf4 (TB_CAP_F4) "\033[15~", // kf5 (TB_CAP_F5) "\033[17~", // kf6 (TB_CAP_F6) "\033[18~", // kf7 (TB_CAP_F7) "\033[19~", // kf8 (TB_CAP_F8) "\033[20~", // kf9 (TB_CAP_F9) "\033[21~", // kf10 (TB_CAP_F10) "\033[23~", // kf11 (TB_CAP_F11) "\033[24~", // kf12 (TB_CAP_F12) "\033[2~", // kich1 (TB_CAP_INSERT) "\033[3~", // kdch1 (TB_CAP_DELETE) "\033[7~", // khome (TB_CAP_HOME) "\033[8~", // kend (TB_CAP_END) "\033[5~", // kpp (TB_CAP_PGUP) "\033[6~", // knp (TB_CAP_PGDN) "\033[A", // kcuu1 (TB_CAP_ARROW_UP) "\033[B", // kcud1 (TB_CAP_ARROW_DOWN) "\033[D", // kcub1 (TB_CAP_ARROW_LEFT) "\033[C", // kcuf1 (TB_CAP_ARROW_RIGHT) "", // kcbt (TB_CAP_BACK_TAB) "\0337\033[?47h", // smcup (TB_CAP_ENTER_CA) "\033[2J\033[?47l\0338", // rmcup (TB_CAP_EXIT_CA) "\033[?25h", // cnorm (TB_CAP_SHOW_CURSOR) "\033[?25l", // civis (TB_CAP_HIDE_CURSOR) "\033[H\033[2J", // clear (TB_CAP_CLEAR_SCREEN) "\033[m\017", // sgr0 (TB_CAP_SGR0) "\033[4m", // smul (TB_CAP_UNDERLINE) "\033[1m", // bold (TB_CAP_BOLD) "\033[5m", // blink (TB_CAP_BLINK) "", // sitm (TB_CAP_ITALIC) "\033[7m", // rev (TB_CAP_REVERSE) "", // smkx (TB_CAP_ENTER_KEYPAD) "", // rmkx (TB_CAP_EXIT_KEYPAD) "", // dim (TB_CAP_DIM) "", // invis (TB_CAP_INVISIBLE) }; static struct { const char *name; const char **caps; const char *alias; } builtin_terms[] = { {"xterm", xterm_caps, "" }, {"linux", linux_caps, "" }, {"screen", screen_caps, "tmux"}, {"rxvt-256color", rxvt_256color_caps, "" }, {"rxvt-unicode", rxvt_unicode_caps, "rxvt"}, {"Eterm", eterm_caps, "" }, {NULL, NULL, NULL }, }; /* END codegen c */ static struct { const char *cap; const uint16_t key; const uint8_t mod; } builtin_mod_caps[] = { // xterm arrows {"\x1b[1;2A", TB_KEY_ARROW_UP, TB_MOD_SHIFT }, {"\x1b[1;3A", TB_KEY_ARROW_UP, TB_MOD_ALT }, {"\x1b[1;4A", TB_KEY_ARROW_UP, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5A", TB_KEY_ARROW_UP, TB_MOD_CTRL }, {"\x1b[1;6A", TB_KEY_ARROW_UP, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7A", TB_KEY_ARROW_UP, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8A", TB_KEY_ARROW_UP, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2B", TB_KEY_ARROW_DOWN, TB_MOD_SHIFT }, {"\x1b[1;3B", TB_KEY_ARROW_DOWN, TB_MOD_ALT }, {"\x1b[1;4B", TB_KEY_ARROW_DOWN, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5B", TB_KEY_ARROW_DOWN, TB_MOD_CTRL }, {"\x1b[1;6B", TB_KEY_ARROW_DOWN, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7B", TB_KEY_ARROW_DOWN, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8B", TB_KEY_ARROW_DOWN, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2C", TB_KEY_ARROW_RIGHT, TB_MOD_SHIFT }, {"\x1b[1;3C", TB_KEY_ARROW_RIGHT, TB_MOD_ALT }, {"\x1b[1;4C", TB_KEY_ARROW_RIGHT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5C", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL }, {"\x1b[1;6C", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7C", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8C", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2D", TB_KEY_ARROW_LEFT, TB_MOD_SHIFT }, {"\x1b[1;3D", TB_KEY_ARROW_LEFT, TB_MOD_ALT }, {"\x1b[1;4D", TB_KEY_ARROW_LEFT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5D", TB_KEY_ARROW_LEFT, TB_MOD_CTRL }, {"\x1b[1;6D", TB_KEY_ARROW_LEFT, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7D", TB_KEY_ARROW_LEFT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8D", TB_KEY_ARROW_LEFT, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, // xterm keys {"\x1b[1;2H", TB_KEY_HOME, TB_MOD_SHIFT }, {"\x1b[1;3H", TB_KEY_HOME, TB_MOD_ALT }, {"\x1b[1;4H", TB_KEY_HOME, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5H", TB_KEY_HOME, TB_MOD_CTRL }, {"\x1b[1;6H", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7H", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8H", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2F", TB_KEY_END, TB_MOD_SHIFT }, {"\x1b[1;3F", TB_KEY_END, TB_MOD_ALT }, {"\x1b[1;4F", TB_KEY_END, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5F", TB_KEY_END, TB_MOD_CTRL }, {"\x1b[1;6F", TB_KEY_END, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7F", TB_KEY_END, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8F", TB_KEY_END, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[2;2~", TB_KEY_INSERT, TB_MOD_SHIFT }, {"\x1b[2;3~", TB_KEY_INSERT, TB_MOD_ALT }, {"\x1b[2;4~", TB_KEY_INSERT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[2;5~", TB_KEY_INSERT, TB_MOD_CTRL }, {"\x1b[2;6~", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[2;7~", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[2;8~", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[3;2~", TB_KEY_DELETE, TB_MOD_SHIFT }, {"\x1b[3;3~", TB_KEY_DELETE, TB_MOD_ALT }, {"\x1b[3;4~", TB_KEY_DELETE, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[3;5~", TB_KEY_DELETE, TB_MOD_CTRL }, {"\x1b[3;6~", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[3;7~", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[3;8~", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[5;2~", TB_KEY_PGUP, TB_MOD_SHIFT }, {"\x1b[5;3~", TB_KEY_PGUP, TB_MOD_ALT }, {"\x1b[5;4~", TB_KEY_PGUP, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[5;5~", TB_KEY_PGUP, TB_MOD_CTRL }, {"\x1b[5;6~", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[5;7~", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[5;8~", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[6;2~", TB_KEY_PGDN, TB_MOD_SHIFT }, {"\x1b[6;3~", TB_KEY_PGDN, TB_MOD_ALT }, {"\x1b[6;4~", TB_KEY_PGDN, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[6;5~", TB_KEY_PGDN, TB_MOD_CTRL }, {"\x1b[6;6~", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[6;7~", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[6;8~", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2P", TB_KEY_F1, TB_MOD_SHIFT }, {"\x1b[1;3P", TB_KEY_F1, TB_MOD_ALT }, {"\x1b[1;4P", TB_KEY_F1, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5P", TB_KEY_F1, TB_MOD_CTRL }, {"\x1b[1;6P", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7P", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8P", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2Q", TB_KEY_F2, TB_MOD_SHIFT }, {"\x1b[1;3Q", TB_KEY_F2, TB_MOD_ALT }, {"\x1b[1;4Q", TB_KEY_F2, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5Q", TB_KEY_F2, TB_MOD_CTRL }, {"\x1b[1;6Q", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7Q", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8Q", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2R", TB_KEY_F3, TB_MOD_SHIFT }, {"\x1b[1;3R", TB_KEY_F3, TB_MOD_ALT }, {"\x1b[1;4R", TB_KEY_F3, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5R", TB_KEY_F3, TB_MOD_CTRL }, {"\x1b[1;6R", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7R", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8R", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[1;2S", TB_KEY_F4, TB_MOD_SHIFT }, {"\x1b[1;3S", TB_KEY_F4, TB_MOD_ALT }, {"\x1b[1;4S", TB_KEY_F4, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[1;5S", TB_KEY_F4, TB_MOD_CTRL }, {"\x1b[1;6S", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[1;7S", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[1;8S", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[15;2~", TB_KEY_F5, TB_MOD_SHIFT }, {"\x1b[15;3~", TB_KEY_F5, TB_MOD_ALT }, {"\x1b[15;4~", TB_KEY_F5, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[15;5~", TB_KEY_F5, TB_MOD_CTRL }, {"\x1b[15;6~", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[15;7~", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[15;8~", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[17;2~", TB_KEY_F6, TB_MOD_SHIFT }, {"\x1b[17;3~", TB_KEY_F6, TB_MOD_ALT }, {"\x1b[17;4~", TB_KEY_F6, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[17;5~", TB_KEY_F6, TB_MOD_CTRL }, {"\x1b[17;6~", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[17;7~", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[17;8~", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[18;2~", TB_KEY_F7, TB_MOD_SHIFT }, {"\x1b[18;3~", TB_KEY_F7, TB_MOD_ALT }, {"\x1b[18;4~", TB_KEY_F7, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[18;5~", TB_KEY_F7, TB_MOD_CTRL }, {"\x1b[18;6~", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[18;7~", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[18;8~", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[19;2~", TB_KEY_F8, TB_MOD_SHIFT }, {"\x1b[19;3~", TB_KEY_F8, TB_MOD_ALT }, {"\x1b[19;4~", TB_KEY_F8, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[19;5~", TB_KEY_F8, TB_MOD_CTRL }, {"\x1b[19;6~", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[19;7~", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[19;8~", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[20;2~", TB_KEY_F9, TB_MOD_SHIFT }, {"\x1b[20;3~", TB_KEY_F9, TB_MOD_ALT }, {"\x1b[20;4~", TB_KEY_F9, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[20;5~", TB_KEY_F9, TB_MOD_CTRL }, {"\x1b[20;6~", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[20;7~", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[20;8~", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[21;2~", TB_KEY_F10, TB_MOD_SHIFT }, {"\x1b[21;3~", TB_KEY_F10, TB_MOD_ALT }, {"\x1b[21;4~", TB_KEY_F10, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[21;5~", TB_KEY_F10, TB_MOD_CTRL }, {"\x1b[21;6~", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[21;7~", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[21;8~", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[23;2~", TB_KEY_F11, TB_MOD_SHIFT }, {"\x1b[23;3~", TB_KEY_F11, TB_MOD_ALT }, {"\x1b[23;4~", TB_KEY_F11, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[23;5~", TB_KEY_F11, TB_MOD_CTRL }, {"\x1b[23;6~", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[23;7~", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[23;8~", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[24;2~", TB_KEY_F12, TB_MOD_SHIFT }, {"\x1b[24;3~", TB_KEY_F12, TB_MOD_ALT }, {"\x1b[24;4~", TB_KEY_F12, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[24;5~", TB_KEY_F12, TB_MOD_CTRL }, {"\x1b[24;6~", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[24;7~", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[24;8~", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, // rxvt arrows {"\x1b[a", TB_KEY_ARROW_UP, TB_MOD_SHIFT }, {"\x1b\x1b[A", TB_KEY_ARROW_UP, TB_MOD_ALT }, {"\x1b\x1b[a", TB_KEY_ARROW_UP, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1bOa", TB_KEY_ARROW_UP, TB_MOD_CTRL }, {"\x1b\x1bOa", TB_KEY_ARROW_UP, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[b", TB_KEY_ARROW_DOWN, TB_MOD_SHIFT }, {"\x1b\x1b[B", TB_KEY_ARROW_DOWN, TB_MOD_ALT }, {"\x1b\x1b[b", TB_KEY_ARROW_DOWN, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1bOb", TB_KEY_ARROW_DOWN, TB_MOD_CTRL }, {"\x1b\x1bOb", TB_KEY_ARROW_DOWN, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[c", TB_KEY_ARROW_RIGHT, TB_MOD_SHIFT }, {"\x1b\x1b[C", TB_KEY_ARROW_RIGHT, TB_MOD_ALT }, {"\x1b\x1b[c", TB_KEY_ARROW_RIGHT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1bOc", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL }, {"\x1b\x1bOc", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b[d", TB_KEY_ARROW_LEFT, TB_MOD_SHIFT }, {"\x1b\x1b[D", TB_KEY_ARROW_LEFT, TB_MOD_ALT }, {"\x1b\x1b[d", TB_KEY_ARROW_LEFT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1bOd", TB_KEY_ARROW_LEFT, TB_MOD_CTRL }, {"\x1b\x1bOd", TB_KEY_ARROW_LEFT, TB_MOD_CTRL | TB_MOD_ALT }, // rxvt keys {"\x1b[7$", TB_KEY_HOME, TB_MOD_SHIFT }, {"\x1b\x1b[7~", TB_KEY_HOME, TB_MOD_ALT }, {"\x1b\x1b[7$", TB_KEY_HOME, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[7^", TB_KEY_HOME, TB_MOD_CTRL }, {"\x1b[7@", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b\x1b[7^", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[7@", TB_KEY_HOME, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b\x1b[8~", TB_KEY_END, TB_MOD_ALT }, {"\x1b\x1b[8$", TB_KEY_END, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[8^", TB_KEY_END, TB_MOD_CTRL }, {"\x1b\x1b[8^", TB_KEY_END, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[8@", TB_KEY_END, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[8@", TB_KEY_END, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[8$", TB_KEY_END, TB_MOD_SHIFT }, {"\x1b\x1b[2~", TB_KEY_INSERT, TB_MOD_ALT }, {"\x1b\x1b[2$", TB_KEY_INSERT, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[2^", TB_KEY_INSERT, TB_MOD_CTRL }, {"\x1b\x1b[2^", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[2@", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[2@", TB_KEY_INSERT, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[2$", TB_KEY_INSERT, TB_MOD_SHIFT }, {"\x1b\x1b[3~", TB_KEY_DELETE, TB_MOD_ALT }, {"\x1b\x1b[3$", TB_KEY_DELETE, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[3^", TB_KEY_DELETE, TB_MOD_CTRL }, {"\x1b\x1b[3^", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[3@", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[3@", TB_KEY_DELETE, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[3$", TB_KEY_DELETE, TB_MOD_SHIFT }, {"\x1b\x1b[5~", TB_KEY_PGUP, TB_MOD_ALT }, {"\x1b\x1b[5$", TB_KEY_PGUP, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[5^", TB_KEY_PGUP, TB_MOD_CTRL }, {"\x1b\x1b[5^", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[5@", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[5@", TB_KEY_PGUP, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[5$", TB_KEY_PGUP, TB_MOD_SHIFT }, {"\x1b\x1b[6~", TB_KEY_PGDN, TB_MOD_ALT }, {"\x1b\x1b[6$", TB_KEY_PGDN, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[6^", TB_KEY_PGDN, TB_MOD_CTRL }, {"\x1b\x1b[6^", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[6@", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[6@", TB_KEY_PGDN, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[6$", TB_KEY_PGDN, TB_MOD_SHIFT }, {"\x1b\x1b[11~", TB_KEY_F1, TB_MOD_ALT }, {"\x1b\x1b[23~", TB_KEY_F1, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[11^", TB_KEY_F1, TB_MOD_CTRL }, {"\x1b\x1b[11^", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[23^", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[23^", TB_KEY_F1, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[23~", TB_KEY_F1, TB_MOD_SHIFT }, {"\x1b\x1b[12~", TB_KEY_F2, TB_MOD_ALT }, {"\x1b\x1b[24~", TB_KEY_F2, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[12^", TB_KEY_F2, TB_MOD_CTRL }, {"\x1b\x1b[12^", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[24^", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[24^", TB_KEY_F2, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[24~", TB_KEY_F2, TB_MOD_SHIFT }, {"\x1b\x1b[13~", TB_KEY_F3, TB_MOD_ALT }, {"\x1b\x1b[25~", TB_KEY_F3, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[13^", TB_KEY_F3, TB_MOD_CTRL }, {"\x1b\x1b[13^", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[25^", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[25^", TB_KEY_F3, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[25~", TB_KEY_F3, TB_MOD_SHIFT }, {"\x1b\x1b[14~", TB_KEY_F4, TB_MOD_ALT }, {"\x1b\x1b[26~", TB_KEY_F4, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[14^", TB_KEY_F4, TB_MOD_CTRL }, {"\x1b\x1b[14^", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[26^", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[26^", TB_KEY_F4, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[26~", TB_KEY_F4, TB_MOD_SHIFT }, {"\x1b\x1b[15~", TB_KEY_F5, TB_MOD_ALT }, {"\x1b\x1b[28~", TB_KEY_F5, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[15^", TB_KEY_F5, TB_MOD_CTRL }, {"\x1b\x1b[15^", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[28^", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[28^", TB_KEY_F5, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[28~", TB_KEY_F5, TB_MOD_SHIFT }, {"\x1b\x1b[17~", TB_KEY_F6, TB_MOD_ALT }, {"\x1b\x1b[29~", TB_KEY_F6, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[17^", TB_KEY_F6, TB_MOD_CTRL }, {"\x1b\x1b[17^", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[29^", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[29^", TB_KEY_F6, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[29~", TB_KEY_F6, TB_MOD_SHIFT }, {"\x1b\x1b[18~", TB_KEY_F7, TB_MOD_ALT }, {"\x1b\x1b[31~", TB_KEY_F7, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[18^", TB_KEY_F7, TB_MOD_CTRL }, {"\x1b\x1b[18^", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[31^", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[31^", TB_KEY_F7, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[31~", TB_KEY_F7, TB_MOD_SHIFT }, {"\x1b\x1b[19~", TB_KEY_F8, TB_MOD_ALT }, {"\x1b\x1b[32~", TB_KEY_F8, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[19^", TB_KEY_F8, TB_MOD_CTRL }, {"\x1b\x1b[19^", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[32^", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[32^", TB_KEY_F8, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[32~", TB_KEY_F8, TB_MOD_SHIFT }, {"\x1b\x1b[20~", TB_KEY_F9, TB_MOD_ALT }, {"\x1b\x1b[33~", TB_KEY_F9, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[20^", TB_KEY_F9, TB_MOD_CTRL }, {"\x1b\x1b[20^", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[33^", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[33^", TB_KEY_F9, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[33~", TB_KEY_F9, TB_MOD_SHIFT }, {"\x1b\x1b[21~", TB_KEY_F10, TB_MOD_ALT }, {"\x1b\x1b[34~", TB_KEY_F10, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[21^", TB_KEY_F10, TB_MOD_CTRL }, {"\x1b\x1b[21^", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[34^", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[34^", TB_KEY_F10, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[34~", TB_KEY_F10, TB_MOD_SHIFT }, {"\x1b\x1b[23~", TB_KEY_F11, TB_MOD_ALT }, {"\x1b\x1b[23$", TB_KEY_F11, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[23^", TB_KEY_F11, TB_MOD_CTRL }, {"\x1b\x1b[23^", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[23@", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[23@", TB_KEY_F11, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[23$", TB_KEY_F11, TB_MOD_SHIFT }, {"\x1b\x1b[24~", TB_KEY_F12, TB_MOD_ALT }, {"\x1b\x1b[24$", TB_KEY_F12, TB_MOD_ALT | TB_MOD_SHIFT }, {"\x1b[24^", TB_KEY_F12, TB_MOD_CTRL }, {"\x1b\x1b[24^", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1b\x1b[24@", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_ALT | TB_MOD_SHIFT}, {"\x1b[24@", TB_KEY_F12, TB_MOD_CTRL | TB_MOD_SHIFT }, {"\x1b[24$", TB_KEY_F12, TB_MOD_SHIFT }, // linux console/putty arrows {"\x1b[A", TB_KEY_ARROW_UP, TB_MOD_SHIFT }, {"\x1b[B", TB_KEY_ARROW_DOWN, TB_MOD_SHIFT }, {"\x1b[C", TB_KEY_ARROW_RIGHT, TB_MOD_SHIFT }, {"\x1b[D", TB_KEY_ARROW_LEFT, TB_MOD_SHIFT }, // more putty arrows {"\x1bOA", TB_KEY_ARROW_UP, TB_MOD_CTRL }, {"\x1b\x1bOA", TB_KEY_ARROW_UP, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1bOB", TB_KEY_ARROW_DOWN, TB_MOD_CTRL }, {"\x1b\x1bOB", TB_KEY_ARROW_DOWN, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1bOC", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL }, {"\x1b\x1bOC", TB_KEY_ARROW_RIGHT, TB_MOD_CTRL | TB_MOD_ALT }, {"\x1bOD", TB_KEY_ARROW_LEFT, TB_MOD_CTRL }, {"\x1b\x1bOD", TB_KEY_ARROW_LEFT, TB_MOD_CTRL | TB_MOD_ALT }, {NULL, 0, 0 }, }; static const unsigned char utf8_length[256] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1}; static const unsigned char utf8_mask[6] = {0x7f, 0x1f, 0x0f, 0x07, 0x03, 0x01}; static int tb_reset(void); static int tb_printf_inner(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *fmt, va_list vl); static int init_term_attrs(void); static int init_term_caps(void); static int init_cap_trie(void); static int cap_trie_add(const char *cap, uint16_t key, uint8_t mod); static int cap_trie_find(const char *buf, size_t nbuf, struct cap_trie_t **last, size_t *depth); static int cap_trie_deinit(struct cap_trie_t *node); static int init_resize_handler(void); static int send_init_escape_codes(void); static int send_clear(void); static int update_term_size(void); static int update_term_size_via_esc(void); static int init_cellbuf(void); static int tb_deinit(void); static int load_terminfo(void); static int load_terminfo_from_path(const char *path, const char *term); static int read_terminfo_path(const char *path); static int parse_terminfo_caps(void); static int load_builtin_caps(void); static const char *get_terminfo_string(int16_t str_offsets_pos, int16_t str_offsets_len, int16_t str_table_pos, int16_t str_table_len, int16_t str_index); static int wait_event(struct tb_event *event, int timeout); static int extract_event(struct tb_event *event); static int extract_esc(struct tb_event *event); static int extract_esc_user(struct tb_event *event, int is_post); static int extract_esc_cap(struct tb_event *event); static int extract_esc_mouse(struct tb_event *event); static int resize_cellbufs(void); static void handle_resize(int sig); static int send_attr(uintattr_t fg, uintattr_t bg); static int send_sgr(uint32_t fg, uint32_t bg, int fg_is_default, int bg_is_default); static int send_cursor_if(int x, int y); static int send_char(int x, int y, uint32_t ch); static int send_cluster(int x, int y, uint32_t *ch, size_t nch); static int convert_num(uint32_t num, char *buf); static int cell_cmp(struct tb_cell *a, struct tb_cell *b); static int cell_copy(struct tb_cell *dst, struct tb_cell *src); static int cell_set(struct tb_cell *cell, uint32_t *ch, size_t nch, uintattr_t fg, uintattr_t bg); static int cell_reserve_ech(struct tb_cell *cell, size_t n); static int cell_free(struct tb_cell *cell); static int cellbuf_init(struct cellbuf_t *c, int w, int h); static int cellbuf_free(struct cellbuf_t *c); static int cellbuf_clear(struct cellbuf_t *c); static int cellbuf_get(struct cellbuf_t *c, int x, int y, struct tb_cell **out); static int cellbuf_resize(struct cellbuf_t *c, int w, int h); static int bytebuf_puts(struct bytebuf_t *b, const char *str); static int bytebuf_nputs(struct bytebuf_t *b, const char *str, size_t nstr); static int bytebuf_shift(struct bytebuf_t *b, size_t n); static int bytebuf_flush(struct bytebuf_t *b, int fd); static int bytebuf_reserve(struct bytebuf_t *b, size_t sz); static int bytebuf_free(struct bytebuf_t *b); int tb_init(void) { return tb_init_file("/dev/tty"); } int tb_init_file(const char *path) { if (global.initialized) { return TB_ERR_INIT_ALREADY; } int ttyfd = open(path, O_RDWR); if (ttyfd < 0) { global.last_errno = errno; return TB_ERR_INIT_OPEN; } global.ttyfd_open = 1; return tb_init_fd(ttyfd); } int tb_init_fd(int ttyfd) { return tb_init_rwfd(ttyfd, ttyfd); } int tb_init_rwfd(int rfd, int wfd) { int rv; tb_reset(); global.ttyfd = rfd == wfd && isatty(rfd) ? rfd : -1; global.rfd = rfd; global.wfd = wfd; do { if_err_break(rv, init_term_attrs()); if_err_break(rv, init_term_caps()); if_err_break(rv, init_cap_trie()); if_err_break(rv, init_resize_handler()); if_err_break(rv, send_init_escape_codes()); if_err_break(rv, send_clear()); if_err_break(rv, update_term_size()); if_err_break(rv, init_cellbuf()); global.initialized = 1; } while (0); if (rv != TB_OK) { tb_deinit(); } return rv; } int tb_shutdown(void) { if_not_init_return(); tb_deinit(); return TB_OK; } int tb_width(void) { if_not_init_return(); return global.width; } int tb_height(void) { if_not_init_return(); return global.height; } int tb_clear(void) { if_not_init_return(); return cellbuf_clear(&global.back); } int tb_set_clear_attrs(uintattr_t fg, uintattr_t bg) { if_not_init_return(); global.fg = fg; global.bg = bg; return TB_OK; } int tb_present(void) { if_not_init_return(); int rv; // TODO Assert global.back.(width,height) == global.front.(width,height) global.last_x = -1; global.last_y = -1; int x, y, i; for (y = 0; y < global.front.height; y++) { for (x = 0; x < global.front.width;) { struct tb_cell *back, *front; if_err_return(rv, cellbuf_get(&global.back, x, y, &back)); if_err_return(rv, cellbuf_get(&global.front, x, y, &front)); int w; { #ifdef TB_OPT_EGC if (back->nech > 0) w = wcswidth((wchar_t *)back->ech, back->nech); else #endif /* wcwidth() simply returns -1 on overflow of wchar_t */ w = wcwidth((wchar_t)back->ch); } if (w < 1) { w = 1; } if (cell_cmp(back, front) != 0) { cell_copy(front, back); send_attr(back->fg, back->bg); if (w > 1 && x >= global.front.width - (w - 1)) { // Not enough room for wide char, send spaces for (i = x; i < global.front.width; i++) { send_char(i, y, ' '); } } else { { #ifdef TB_OPT_EGC if (back->nech > 0) send_cluster(x, y, back->ech, back->nech); else #endif send_char(x, y, back->ch); } // When wcwidth>1, we need to advance the cursor by more // than 1, thereby skipping some cells. Set these skipped // cells to an invalid codepoint in the front buffer, so // that if this cell is later replaced by a wcwidth==1 char, // we'll get a cell_cmp diff for the skipped cells and // properly re-render. for (i = 1; i < w; i++) { struct tb_cell *front_wide; uint32_t invalid = -1; if_err_return(rv, cellbuf_get(&global.front, x + i, y, &front_wide)); if_err_return(rv, cell_set(front_wide, &invalid, 1, -1, -1)); } } } x += w; } } if_err_return(rv, send_cursor_if(global.cursor_x, global.cursor_y)); if_err_return(rv, bytebuf_flush(&global.out, global.wfd)); return TB_OK; } int tb_invalidate(void) { int rv; if_not_init_return(); if_err_return(rv, resize_cellbufs()); return TB_OK; } int tb_set_cursor(int cx, int cy) { if_not_init_return(); int rv; if (cx < 0) cx = 0; if (cy < 0) cy = 0; if (global.cursor_x == -1) { if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_SHOW_CURSOR])); } if_err_return(rv, send_cursor_if(cx, cy)); global.cursor_x = cx; global.cursor_y = cy; return TB_OK; } int tb_hide_cursor(void) { if_not_init_return(); int rv; if (global.cursor_x >= 0) { if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_HIDE_CURSOR])); } global.cursor_x = -1; global.cursor_y = -1; return TB_OK; } int tb_set_cell(int x, int y, uint32_t ch, uintattr_t fg, uintattr_t bg) { return tb_set_cell_ex(x, y, &ch, 1, fg, bg); } int tb_set_cell_ex(int x, int y, uint32_t *ch, size_t nch, uintattr_t fg, uintattr_t bg) { if_not_init_return(); int rv; struct tb_cell *cell; if_err_return(rv, cellbuf_get(&global.back, x, y, &cell)); if_err_return(rv, cell_set(cell, ch, nch, fg, bg)); return TB_OK; } int tb_extend_cell(int x, int y, uint32_t ch) { if_not_init_return(); #ifdef TB_OPT_EGC int rv; struct tb_cell *cell; size_t nech; if_err_return(rv, cellbuf_get(&global.back, x, y, &cell)); if (cell->nech > 0) { // append to ech nech = cell->nech + 1; if_err_return(rv, cell_reserve_ech(cell, nech)); cell->ech[nech - 1] = ch; } else { // make new ech nech = 2; if_err_return(rv, cell_reserve_ech(cell, nech)); cell->ech[0] = cell->ch; cell->ech[1] = ch; } cell->ech[nech] = '\0'; cell->nech = nech; return TB_OK; #else (void)x; (void)y; (void)ch; return TB_ERR; #endif } int tb_set_input_mode(int mode) { if_not_init_return(); if (mode == TB_INPUT_CURRENT) { return global.input_mode; } if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == 0) { mode |= TB_INPUT_ESC; } if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == (TB_INPUT_ESC | TB_INPUT_ALT)) { mode &= ~TB_INPUT_ALT; } if (mode & TB_INPUT_MOUSE) { bytebuf_puts(&global.out, TB_HARDCAP_ENTER_MOUSE); bytebuf_flush(&global.out, global.wfd); } else { bytebuf_puts(&global.out, TB_HARDCAP_EXIT_MOUSE); bytebuf_flush(&global.out, global.wfd); } global.input_mode = mode; return TB_OK; } int tb_set_output_mode(int mode) { if_not_init_return(); switch (mode) { case TB_OUTPUT_CURRENT: return global.output_mode; case TB_OUTPUT_NORMAL: case TB_OUTPUT_256: case TB_OUTPUT_216: case TB_OUTPUT_GRAYSCALE: #if TB_OPT_ATTR_W >= 32 case TB_OUTPUT_TRUECOLOR: #endif global.last_fg = ~global.fg; global.last_bg = ~global.bg; global.output_mode = mode; return TB_OK; } return TB_ERR; } int tb_peek_event(struct tb_event *event, int timeout_ms) { if_not_init_return(); return wait_event(event, timeout_ms); } int tb_poll_event(struct tb_event *event) { if_not_init_return(); return wait_event(event, -1); } int tb_get_fds(int *ttyfd, int *resizefd) { if_not_init_return(); *ttyfd = global.rfd; *resizefd = global.resize_pipefd[0]; return TB_OK; } int tb_print(int x, int y, uintattr_t fg, uintattr_t bg, const char *str) { return tb_print_ex(x, y, fg, bg, NULL, str); } int tb_print_ex(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *str) { int rv; uint32_t uni; int w, ix = x; if (out_w) { *out_w = 0; } while (*str) { rv = tb_utf8_char_to_unicode(&uni, str); if (rv < 0) { uni = 0xfffd; // replace invalid UTF-8 char with U+FFFD str += rv * -1; } else if (rv > 0) { str += rv; } else { break; // shouldn't get here } w = wcwidth((wchar_t)uni); if (w < 0) w = 1; if (w == 0 && x > ix) { if_err_return(rv, tb_extend_cell(x - 1, y, uni)); } else { if_err_return(rv, tb_set_cell(x, y, uni, fg, bg)); } x += w; if (out_w) { *out_w += w; } } return TB_OK; } int tb_printf(int x, int y, uintattr_t fg, uintattr_t bg, const char *fmt, ...) { int rv; va_list vl; va_start(vl, fmt); rv = tb_printf_inner(x, y, fg, bg, NULL, fmt, vl); va_end(vl); return rv; } int tb_printf_ex(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *fmt, ...) { int rv; va_list vl; va_start(vl, fmt); rv = tb_printf_inner(x, y, fg, bg, out_w, fmt, vl); va_end(vl); return rv; } int tb_send(const char *buf, size_t nbuf) { return bytebuf_nputs(&global.out, buf, nbuf); } int tb_sendf(const char *fmt, ...) { int rv; char buf[TB_OPT_PRINTF_BUF]; va_list vl; va_start(vl, fmt); rv = vsnprintf(buf, sizeof(buf), fmt, vl); va_end(vl); if (rv < 0 || rv >= (int)sizeof(buf)) { return TB_ERR; } return tb_send(buf, (size_t)rv); } int tb_set_func(int fn_type, int (*fn)(struct tb_event *, size_t *)) { switch (fn_type) { case TB_FUNC_EXTRACT_PRE: global.fn_extract_esc_pre = fn; return TB_OK; case TB_FUNC_EXTRACT_POST: global.fn_extract_esc_post = fn; return TB_OK; } return TB_ERR; } struct tb_cell *tb_cell_buffer(void) { if (!global.initialized) return NULL; return global.back.cells; } int tb_utf8_char_length(char c) { return utf8_length[(unsigned char)c]; } int tb_utf8_char_to_unicode(uint32_t *out, const char *c) { if (*c == '\0') return 0; int i; unsigned char len = tb_utf8_char_length(*c); unsigned char mask = utf8_mask[len - 1]; uint32_t result = c[0] & mask; for (i = 1; i < len && c[i] != '\0'; ++i) { result <<= 6; result |= c[i] & 0x3f; } if (i != len) return i * -1; *out = result; return (int)len; } int tb_utf8_unicode_to_char(char *out, uint32_t c) { int len = 0; int first; int i; if (c < 0x80) { first = 0; len = 1; } else if (c < 0x800) { first = 0xc0; len = 2; } else if (c < 0x10000) { first = 0xe0; len = 3; } else if (c < 0x200000) { first = 0xf0; len = 4; } else if (c < 0x4000000) { first = 0xf8; len = 5; } else { first = 0xfc; len = 6; } for (i = len - 1; i > 0; --i) { out[i] = (c & 0x3f) | 0x80; c >>= 6; } out[0] = c | first; out[len] = '\0'; return len; } int tb_last_errno(void) { return global.last_errno; } const char *tb_strerror(int err) { switch (err) { case TB_OK: return "Success"; case TB_ERR_NEED_MORE: return "Not enough input"; case TB_ERR_INIT_ALREADY: return "Termbox initialized already"; case TB_ERR_MEM: return "Out of memory"; case TB_ERR_NO_EVENT: return "No event"; case TB_ERR_NO_TERM: return "No TERM in environment"; case TB_ERR_NOT_INIT: return "Termbox not initialized"; case TB_ERR_OUT_OF_BOUNDS: return "Out of bounds"; case TB_ERR_UNSUPPORTED_TERM: return "Unsupported terminal"; case TB_ERR_CAP_COLLISION: return "Termcaps collision"; case TB_ERR_RESIZE_SSCANF: return "Terminal width/height not received by sscanf() after " "resize"; case TB_ERR: case TB_ERR_INIT_OPEN: case TB_ERR_READ: case TB_ERR_RESIZE_IOCTL: case TB_ERR_RESIZE_PIPE: case TB_ERR_RESIZE_SIGACTION: case TB_ERR_POLL: case TB_ERR_TCGETATTR: case TB_ERR_TCSETATTR: case TB_ERR_RESIZE_WRITE: case TB_ERR_RESIZE_POLL: case TB_ERR_RESIZE_READ: default: strerror_r(global.last_errno, global.errbuf, sizeof(global.errbuf)); return (const char *)global.errbuf; } } int tb_has_truecolor(void) { #if TB_OPT_ATTR_W >= 32 return 1; #else return 0; #endif } int tb_has_egc(void) { #ifdef TB_OPT_EGC return 1; #else return 0; #endif } int tb_attr_width(void) { return TB_OPT_ATTR_W; } const char *tb_version(void) { return TB_VERSION_STR; } static int tb_reset(void) { int ttyfd_open = global.ttyfd_open; memset(&global, 0, sizeof(global)); global.ttyfd = -1; global.rfd = -1; global.wfd = -1; global.ttyfd_open = ttyfd_open; global.resize_pipefd[0] = -1; global.resize_pipefd[1] = -1; global.width = -1; global.height = -1; global.cursor_x = -1; global.cursor_y = -1; global.last_x = -1; global.last_y = -1; global.fg = TB_DEFAULT; global.bg = TB_DEFAULT; global.last_fg = ~global.fg; global.last_bg = ~global.bg; global.input_mode = TB_INPUT_ESC; global.output_mode = TB_OUTPUT_NORMAL; return TB_OK; } static int init_term_attrs(void) { if (global.ttyfd < 0) { return TB_OK; } if (tcgetattr(global.ttyfd, &global.orig_tios) != 0) { global.last_errno = errno; return TB_ERR_TCGETATTR; } struct termios tios; memcpy(&tios, &global.orig_tios, sizeof(tios)); global.has_orig_tios = 1; cfmakeraw(&tios); tios.c_cc[VMIN] = 1; tios.c_cc[VTIME] = 0; if (tcsetattr(global.ttyfd, TCSAFLUSH, &tios) != 0) { global.last_errno = errno; return TB_ERR_TCSETATTR; } return TB_OK; } int tb_printf_inner(int x, int y, uintattr_t fg, uintattr_t bg, size_t *out_w, const char *fmt, va_list vl) { int rv; char buf[TB_OPT_PRINTF_BUF]; rv = vsnprintf(buf, sizeof(buf), fmt, vl); if (rv < 0 || rv >= (int)sizeof(buf)) { return TB_ERR; } return tb_print_ex(x, y, fg, bg, out_w, buf); } static int init_term_caps(void) { if (load_terminfo() == TB_OK) { return parse_terminfo_caps(); } return load_builtin_caps(); } static int init_cap_trie(void) { int rv, i; // Add caps from terminfo or built-in // // Collisions are expected as some terminfo entries have dupes. (For // example, att605-pc collides on TB_CAP_F4 and TB_CAP_DELETE.) First cap // in TB_CAP_* index order will win. // // TODO Reorder TB_CAP_* so more critical caps come first. for (i = 0; i < TB_CAP__COUNT_KEYS; i++) { rv = cap_trie_add(global.caps[i], tb_key_i(i), 0); if (rv != TB_OK && rv != TB_ERR_CAP_COLLISION) return rv; } // Add built-in mod caps // // Collisions are OK here as well. This can happen if global.caps collides // with builtin_mod_caps. It is desirable to give precedence to global.caps // here. for (i = 0; builtin_mod_caps[i].cap != NULL; i++) { rv = cap_trie_add(builtin_mod_caps[i].cap, builtin_mod_caps[i].key, builtin_mod_caps[i].mod); if (rv != TB_OK && rv != TB_ERR_CAP_COLLISION) return rv; } return TB_OK; } static int cap_trie_add(const char *cap, uint16_t key, uint8_t mod) { struct cap_trie_t *next, *node = &global.cap_trie; size_t i, j; if (!cap || strlen(cap) <= 0) return TB_OK; // Nothing to do for empty caps for (i = 0; cap[i] != '\0'; i++) { char c = cap[i]; next = NULL; // Check if c is already a child of node for (j = 0; j < node->nchildren; j++) { if (node->children[j].c == c) { next = &node->children[j]; break; } } if (!next) { // We need to add a new child to node node->nchildren += 1; node->children = tb_realloc(node->children, sizeof(*node) * node->nchildren); if (!node->children) { return TB_ERR_MEM; } next = &node->children[node->nchildren - 1]; memset(next, 0, sizeof(*next)); next->c = c; } // Continue node = next; } if (node->is_leaf) { // Already a leaf here return TB_ERR_CAP_COLLISION; } node->is_leaf = 1; node->key = key; node->mod = mod; return TB_OK; } static int cap_trie_find(const char *buf, size_t nbuf, struct cap_trie_t **last, size_t *depth) { struct cap_trie_t *next, *node = &global.cap_trie; size_t i, j; *last = node; *depth = 0; for (i = 0; i < nbuf; i++) { char c = buf[i]; next = NULL; // Find c in node.children for (j = 0; j < node->nchildren; j++) { if (node->children[j].c == c) { next = &node->children[j]; break; } } if (!next) { // Not found return TB_OK; } node = next; *last = node; *depth += 1; if (node->is_leaf && node->nchildren < 1) { break; } } return TB_OK; } static int cap_trie_deinit(struct cap_trie_t *node) { size_t j; for (j = 0; j < node->nchildren; j++) { cap_trie_deinit(&node->children[j]); } if (node->children) { tb_free(node->children); } memset(node, 0, sizeof(*node)); return TB_OK; } static int init_resize_handler(void) { if (pipe(global.resize_pipefd) != 0) { global.last_errno = errno; return TB_ERR_RESIZE_PIPE; } struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handle_resize; if (sigaction(SIGWINCH, &sa, NULL) != 0) { global.last_errno = errno; return TB_ERR_RESIZE_SIGACTION; } return TB_OK; } static int send_init_escape_codes(void) { int rv; if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_ENTER_CA])); if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_ENTER_KEYPAD])); if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_HIDE_CURSOR])); return TB_OK; } static int send_clear(void) { int rv; if_err_return(rv, send_attr(global.fg, global.bg)); if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_CLEAR_SCREEN])); if_err_return(rv, send_cursor_if(global.cursor_x, global.cursor_y)); if_err_return(rv, bytebuf_flush(&global.out, global.wfd)); global.last_x = -1; global.last_y = -1; return TB_OK; } static int update_term_size(void) { int rv, ioctl_errno; if (global.ttyfd < 0) { return TB_OK; } struct winsize sz; memset(&sz, 0, sizeof(sz)); // Try ioctl TIOCGWINSZ if (ioctl(global.ttyfd, TIOCGWINSZ, &sz) == 0) { global.width = sz.ws_col; global.height = sz.ws_row; return TB_OK; } ioctl_errno = errno; // Try >cursor(9999,9999), >u7, <u6 if_ok_return(rv, update_term_size_via_esc()); global.last_errno = ioctl_errno; return TB_ERR_RESIZE_IOCTL; } static int update_term_size_via_esc(void) { #ifndef TB_RESIZE_FALLBACK_MS #define TB_RESIZE_FALLBACK_MS 1000 #endif char *move_and_report = "\x1b[9999;9999H\x1b[6n"; ssize_t write_rv = write(global.wfd, move_and_report, strlen(move_and_report)); if (write_rv != (ssize_t)strlen(move_and_report)) { return TB_ERR_RESIZE_WRITE; } fd_set fds; FD_ZERO(&fds); FD_SET(global.rfd, &fds); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = TB_RESIZE_FALLBACK_MS * 1000; int select_rv = select(global.rfd + 1, &fds, NULL, NULL, &timeout); if (select_rv != 1) { global.last_errno = errno; return TB_ERR_RESIZE_POLL; } char buf[TB_OPT_READ_BUF]; ssize_t read_rv = read(global.rfd, buf, sizeof(buf) - 1); if (read_rv < 1) { global.last_errno = errno; return TB_ERR_RESIZE_READ; } buf[read_rv] = '\0'; int rw, rh; if (sscanf(buf, "\x1b[%d;%dR", &rh, &rw) != 2) { return TB_ERR_RESIZE_SSCANF; } global.width = rw; global.height = rh; return TB_OK; } static int init_cellbuf(void) { int rv; if_err_return(rv, cellbuf_init(&global.back, global.width, global.height)); if_err_return(rv, cellbuf_init(&global.front, global.width, global.height)); if_err_return(rv, cellbuf_clear(&global.back)); if_err_return(rv, cellbuf_clear(&global.front)); return TB_OK; } static int tb_deinit(void) { if (global.caps[0] != NULL && global.wfd >= 0) { bytebuf_puts(&global.out, global.caps[TB_CAP_SHOW_CURSOR]); bytebuf_puts(&global.out, global.caps[TB_CAP_SGR0]); bytebuf_puts(&global.out, global.caps[TB_CAP_CLEAR_SCREEN]); bytebuf_puts(&global.out, global.caps[TB_CAP_EXIT_CA]); bytebuf_puts(&global.out, global.caps[TB_CAP_EXIT_KEYPAD]); bytebuf_puts(&global.out, TB_HARDCAP_EXIT_MOUSE); bytebuf_flush(&global.out, global.wfd); } if (global.ttyfd >= 0) { if (global.has_orig_tios) { tcsetattr(global.ttyfd, TCSAFLUSH, &global.orig_tios); } if (global.ttyfd_open) { close(global.ttyfd); global.ttyfd_open = 0; } } sigaction(SIGWINCH, &(struct sigaction){.sa_handler = SIG_DFL}, NULL); if (global.resize_pipefd[0] >= 0) close(global.resize_pipefd[0]); if (global.resize_pipefd[1] >= 0) close(global.resize_pipefd[1]); cellbuf_free(&global.back); cellbuf_free(&global.front); bytebuf_free(&global.in); bytebuf_free(&global.out); if (global.terminfo) tb_free(global.terminfo); cap_trie_deinit(&global.cap_trie); tb_reset(); return TB_OK; } static int load_terminfo(void) { int rv; char tmp[TB_PATH_MAX]; // See terminfo(5) "Fetching Compiled Descriptions" for a description of // this behavior. Some of these paths are compile-time ncurses options, so // best guesses are used here. const char *term = getenv("TERM"); if (!term) { return TB_ERR; } // If TERMINFO is set, try that directory and stop const char *terminfo = getenv("TERMINFO"); if (terminfo) { return load_terminfo_from_path(terminfo, term); } // Next try ~/.terminfo const char *home = getenv("HOME"); if (home) { snprintf_or_return(rv, tmp, sizeof(tmp), "%s/.terminfo", home); if_ok_return(rv, load_terminfo_from_path(tmp, term)); } // Next try TERMINFO_DIRS // // Note, empty entries are supposed to be interpretted as the "compiled-in // default", which is of course system-dependent. Previously /etc/terminfo // was used here. Let's skip empty entries altogether rather than give // precedence to a guess, and check common paths after this loop. const char *dirs = getenv("TERMINFO_DIRS"); if (dirs) { snprintf_or_return(rv, tmp, sizeof(tmp), "%s", dirs); char *dir = strtok(tmp, ":"); while (dir) { const char *cdir = dir; if (*cdir != '\0') { if_ok_return(rv, load_terminfo_from_path(cdir, term)); } dir = strtok(NULL, ":"); } } #ifdef TB_TERMINFO_DIR if_ok_return(rv, load_terminfo_from_path(TB_TERMINFO_DIR, term)); #endif if_ok_return(rv, load_terminfo_from_path("/usr/local/etc/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/usr/local/share/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/usr/local/lib/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/etc/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/usr/share/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/usr/lib/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/usr/share/lib/terminfo", term)); if_ok_return(rv, load_terminfo_from_path("/lib/terminfo", term)); return TB_ERR; } static int load_terminfo_from_path(const char *path, const char *term) { int rv; char tmp[TB_PATH_MAX]; // Look for term at this terminfo location, e.g., <terminfo>/x/xterm snprintf_or_return(rv, tmp, sizeof(tmp), "%s/%c/%s", path, term[0], term); if_ok_return(rv, read_terminfo_path(tmp)); #ifdef __APPLE__ // Try the Darwin equivalent path, e.g., <terminfo>/78/xterm snprintf_or_return(rv, tmp, sizeof(tmp), "%s/%x/%s", path, term[0], term); return read_terminfo_path(tmp); #endif return TB_ERR; } static int read_terminfo_path(const char *path) { FILE *fp = fopen(path, "rb"); if (!fp) { return TB_ERR; } struct stat st; if (fstat(fileno(fp), &st) != 0) { fclose(fp); return TB_ERR; } size_t fsize = st.st_size; char *data = tb_malloc(fsize); if (!data) { fclose(fp); return TB_ERR; } if (fread(data, 1, fsize, fp) != fsize) { fclose(fp); tb_free(data); return TB_ERR; } global.terminfo = data; global.nterminfo = fsize; fclose(fp); return TB_OK; } static int parse_terminfo_caps(void) { // See term(5) "LEGACY STORAGE FORMAT" and "EXTENDED STORAGE FORMAT" for a // description of this behavior. // Ensure there's at least a header's worth of data if (global.nterminfo < 6) { return TB_ERR; } int16_t *header = (int16_t *)global.terminfo; // header[0] the magic number (octal 0432 or 01036) // header[1] the size, in bytes, of the names section // header[2] the number of bytes in the boolean section // header[3] the number of short integers in the numbers section // header[4] the number of offsets (short integers) in the strings section // header[5] the size, in bytes, of the string table // Legacy ints are 16-bit, extended ints are 32-bit const int bytes_per_int = header[0] == 01036 ? 4 // 32-bit : 2; // 16-bit // > Between the boolean section and the number section, a null byte will be // > inserted, if necessary, to ensure that the number section begins on an // > even byte const int align_offset = (header[1] + header[2]) % 2 != 0 ? 1 : 0; const int pos_str_offsets = (6 * sizeof(int16_t)) // header (12 bytes) + header[1] // length of names section + header[2] // length of boolean section + align_offset + (header[3] * bytes_per_int); // length of numbers section const int pos_str_table = pos_str_offsets + (header[4] * sizeof(int16_t)); // length of string offsets table // Load caps int i; for (i = 0; i < TB_CAP__COUNT; i++) { const char *cap = get_terminfo_string(pos_str_offsets, header[4], pos_str_table, header[5], terminfo_cap_indexes[i]); if (!cap) { // Something is not right return TB_ERR; } global.caps[i] = cap; } return TB_OK; } static int load_builtin_caps(void) { int i, j; const char *term = getenv("TERM"); if (!term) { return TB_ERR_NO_TERM; } // Check for exact TERM match for (i = 0; builtin_terms[i].name != NULL; i++) { if (strcmp(term, builtin_terms[i].name) == 0) { for (j = 0; j < TB_CAP__COUNT; j++) { global.caps[j] = builtin_terms[i].caps[j]; } return TB_OK; } } // Check for partial TERM or alias match for (i = 0; builtin_terms[i].name != NULL; i++) { if (strstr(term, builtin_terms[i].name) != NULL || (*(builtin_terms[i].alias) != '\0' && strstr(term, builtin_terms[i].alias) != NULL)) { for (j = 0; j < TB_CAP__COUNT; j++) { global.caps[j] = builtin_terms[i].caps[j]; } return TB_OK; } } return TB_ERR_UNSUPPORTED_TERM; } static const char *get_terminfo_string(int16_t str_offsets_pos, int16_t str_offsets_len, int16_t str_table_pos, int16_t str_table_len, int16_t str_index) { const int str_byte_index = (int)str_index * (int)sizeof(int16_t); if (str_byte_index >= (int)str_offsets_len * (int)sizeof(int16_t)) { // An offset beyond the table indicates absent // See `convert_strings` in tinfo `read_entry.c` return ""; } const int16_t *str_offset = (int16_t *)(global.terminfo + (int)str_offsets_pos + str_byte_index); if ((char *)str_offset >= global.terminfo + global.nterminfo) { // str_offset points beyond end of entry // Truncated/corrupt terminfo entry? return NULL; } if (*str_offset < 0 || *str_offset >= str_table_len) { // A negative offset indicates absent // An offset beyond the table indicates absent // See `convert_strings` in tinfo `read_entry.c` return ""; } if (((size_t)((int)str_table_pos + (int)*str_offset)) >= global.nterminfo) { // string points beyond end of entry // Truncated/corrupt terminfo entry? return NULL; } return ( const char *)(global.terminfo + (int)str_table_pos + (int)*str_offset); } static int wait_event(struct tb_event *event, int timeout) { int rv; char buf[TB_OPT_READ_BUF]; memset(event, 0, sizeof(*event)); if_ok_return(rv, extract_event(event)); fd_set fds; struct timeval tv; tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000; do { FD_ZERO(&fds); FD_SET(global.rfd, &fds); FD_SET(global.resize_pipefd[0], &fds); int maxfd = global.resize_pipefd[0] > global.rfd ? global.resize_pipefd[0] : global.rfd; int select_rv = select(maxfd + 1, &fds, NULL, NULL, (timeout < 0) ? NULL : &tv); if (select_rv < 0) { // Let EINTR/EAGAIN bubble up global.last_errno = errno; return TB_ERR_POLL; } else if (select_rv == 0) { return TB_ERR_NO_EVENT; } int tty_has_events = (FD_ISSET(global.rfd, &fds)); int resize_has_events = (FD_ISSET(global.resize_pipefd[0], &fds)); if (tty_has_events) { ssize_t read_rv = read(global.rfd, buf, sizeof(buf)); if (read_rv < 0) { global.last_errno = errno; return TB_ERR_READ; } else if (read_rv > 0) { bytebuf_nputs(&global.in, buf, read_rv); } } if (resize_has_events) { int ignore = 0; read(global.resize_pipefd[0], &ignore, sizeof(ignore)); // TODO Harden against errors encountered mid-resize if_err_return(rv, update_term_size()); if_err_return(rv, resize_cellbufs()); event->type = TB_EVENT_RESIZE; event->w = global.width; event->h = global.height; return TB_OK; } memset(event, 0, sizeof(*event)); if_ok_return(rv, extract_event(event)); } while (timeout == -1); return rv; } static int extract_event(struct tb_event *event) { int rv; struct bytebuf_t *in = &global.in; if (in->len == 0) { return TB_ERR; } if (in->buf[0] == '\x1b') { // Escape sequence? // In TB_INPUT_ESC, skip if the buffer is a single escape char if (!((global.input_mode & TB_INPUT_ESC) && in->len == 1)) { if_ok_or_need_more_return(rv, extract_esc(event)); } // Escape key? if (global.input_mode & TB_INPUT_ESC) { event->type = TB_EVENT_KEY; event->ch = 0; event->key = TB_KEY_ESC; event->mod = 0; bytebuf_shift(in, 1); return TB_OK; } // Recurse for alt key event->mod |= TB_MOD_ALT; bytebuf_shift(in, 1); return extract_event(event); } // ASCII control key? if ((uint16_t)in->buf[0] < TB_KEY_SPACE || in->buf[0] == TB_KEY_BACKSPACE2) { event->type = TB_EVENT_KEY; event->ch = 0; event->key = (uint16_t)in->buf[0]; event->mod |= TB_MOD_CTRL; bytebuf_shift(in, 1); return TB_OK; } // UTF-8? if (in->len >= (size_t)tb_utf8_char_length(in->buf[0])) { event->type = TB_EVENT_KEY; tb_utf8_char_to_unicode(&event->ch, in->buf); event->key = 0; bytebuf_shift(in, tb_utf8_char_length(in->buf[0])); return TB_OK; } // Need more input return TB_ERR; } static int extract_esc(struct tb_event *event) { int rv; if_ok_or_need_more_return(rv, extract_esc_user(event, 0)); if_ok_or_need_more_return(rv, extract_esc_cap(event)); if_ok_or_need_more_return(rv, extract_esc_mouse(event)); if_ok_or_need_more_return(rv, extract_esc_user(event, 1)); return TB_ERR; } static int extract_esc_user(struct tb_event *event, int is_post) { int rv; size_t consumed = 0; struct bytebuf_t *in = &global.in; int (*fn)(struct tb_event *, size_t *); fn = is_post ? global.fn_extract_esc_post : global.fn_extract_esc_pre; if (!fn) { return TB_ERR; } rv = fn(event, &consumed); if (rv == TB_OK) { bytebuf_shift(in, consumed); } if_ok_or_need_more_return(rv, rv); return TB_ERR; } static int extract_esc_cap(struct tb_event *event) { int rv; struct bytebuf_t *in = &global.in; struct cap_trie_t *node; size_t depth; if_err_return(rv, cap_trie_find(in->buf, in->len, &node, &depth)); if (node->is_leaf) { // Found a leaf node event->type = TB_EVENT_KEY; event->ch = 0; event->key = node->key; event->mod = node->mod; bytebuf_shift(in, depth); return TB_OK; } else if (node->nchildren > 0 && in->len <= depth) { // Found a branch node (not enough input) return TB_ERR_NEED_MORE; } return TB_ERR; } static int extract_esc_mouse(struct tb_event *event) { struct bytebuf_t *in = &global.in; enum type { TYPE_VT200 = 0, TYPE_1006, TYPE_1015, TYPE_MAX }; const char *cmp[TYPE_MAX] = {// // X10 mouse encoding, the simplest one // \x1b [ M Cb Cx Cy [TYPE_VT200] = "\x1b[M", // xterm 1006 extended mode or urxvt 1015 extended mode // xterm: \x1b [ < Cb ; Cx ; Cy (M or m) [TYPE_1006] = "\x1b[<", // urxvt: \x1b [ Cb ; Cx ; Cy M [TYPE_1015] = "\x1b["}; enum type type = 0; int ret = TB_ERR; // Unrolled at compile-time (probably) for (; type < TYPE_MAX; type++) { size_t size = strlen(cmp[type]); if (in->len >= size && (strncmp(cmp[type], in->buf, size)) == 0) { break; } } if (type == TYPE_MAX) { ret = TB_ERR; // No match return ret; } size_t buf_shift = 0; switch (type) { case TYPE_VT200: if (in->len >= 6) { int b = in->buf[3] - 0x20; int fail = 0; switch (b & 3) { case 0: event->key = ((b & 64) != 0) ? TB_KEY_MOUSE_WHEEL_UP : TB_KEY_MOUSE_LEFT; break; case 1: event->key = ((b & 64) != 0) ? TB_KEY_MOUSE_WHEEL_DOWN : TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: ret = TB_ERR; fail = 1; break; } if (!fail) { if ((b & 32) != 0) { event->mod |= TB_MOD_MOTION; } // the coord is 1,1 for upper left event->x = ((uint8_t)in->buf[4]) - 0x21; event->y = ((uint8_t)in->buf[5]) - 0x21; ret = TB_OK; } buf_shift = 6; } break; case TYPE_1006: // fallthrough case TYPE_1015: { size_t index_fail = (size_t)-1; enum { FIRST_M = 0, FIRST_SEMICOLON, LAST_SEMICOLON, FIRST_LAST_MAX }; size_t indices[FIRST_LAST_MAX] = {index_fail, index_fail, index_fail}; int m_is_capital = 0; for (size_t i = 0; i < in->len; i++) { if (in->buf[i] == ';') { if (indices[FIRST_SEMICOLON] == index_fail) { indices[FIRST_SEMICOLON] = i; } else { indices[LAST_SEMICOLON] = i; } } else if (indices[FIRST_M] == index_fail) { if (in->buf[i] == 'm' || in->buf[i] == 'M') { m_is_capital = (in->buf[i] == 'M'); indices[FIRST_M] = i; } } } if (indices[FIRST_M] == index_fail || indices[FIRST_SEMICOLON] == index_fail || indices[LAST_SEMICOLON] == index_fail) { ret = TB_ERR; } else { int start = (type == TYPE_1015 ? 2 : 3); unsigned n1 = strtoul(&in->buf[start], NULL, 10); unsigned n2 = strtoul(&in->buf[indices[FIRST_SEMICOLON] + 1], NULL, 10); unsigned n3 = strtoul(&in->buf[indices[LAST_SEMICOLON] + 1], NULL, 10); if (type == TYPE_1015) { n1 -= 0x20; } int fail = 0; switch (n1 & 3) { case 0: event->key = ((n1 & 64) != 0) ? TB_KEY_MOUSE_WHEEL_UP : TB_KEY_MOUSE_LEFT; break; case 1: event->key = ((n1 & 64) != 0) ? TB_KEY_MOUSE_WHEEL_DOWN : TB_KEY_MOUSE_MIDDLE; break; case 2: event->key = TB_KEY_MOUSE_RIGHT; break; case 3: event->key = TB_KEY_MOUSE_RELEASE; break; default: ret = TB_ERR; fail = 1; break; } buf_shift = in->len; if (!fail) { if (!m_is_capital) { // on xterm mouse release is signaled by lowercase m event->key = TB_KEY_MOUSE_RELEASE; } if ((n1 & 32) != 0) { event->mod |= TB_MOD_MOTION; } event->x = ((uint8_t)n2) - 1; event->y = ((uint8_t)n3) - 1; ret = TB_OK; } } } break; case TYPE_MAX: ret = TB_ERR; } if (buf_shift > 0) { bytebuf_shift(in, buf_shift); } if (ret == TB_OK) { event->type = TB_EVENT_MOUSE; } return ret; } static int resize_cellbufs(void) { int rv; if_err_return(rv, cellbuf_resize(&global.back, global.width, global.height)); if_err_return(rv, cellbuf_resize(&global.front, global.width, global.height)); if_err_return(rv, cellbuf_clear(&global.front)); if_err_return(rv, send_clear()); return TB_OK; } static void handle_resize(int sig) { int errno_copy = errno; write(global.resize_pipefd[1], &sig, sizeof(sig)); errno = errno_copy; } static int send_attr(uintattr_t fg, uintattr_t bg) { int rv; if (fg == global.last_fg && bg == global.last_bg) { return TB_OK; } if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_SGR0])); uint32_t cfg, cbg; switch (global.output_mode) { default: case TB_OUTPUT_NORMAL: // The minus 1 below is because our colors are 1-indexed starting // from black. Black is represented by a 30, 40, 90, or 100 for fg, // bg, bright fg, or bright bg respectively. Red is 31, 41, 91, // 101, etc. cfg = (fg & TB_BRIGHT ? 90 : 30) + (fg & 0x0f) - 1; cbg = (bg & TB_BRIGHT ? 100 : 40) + (bg & 0x0f) - 1; break; case TB_OUTPUT_256: cfg = fg & 0xff; cbg = bg & 0xff; if (fg & TB_HI_BLACK) cfg = 0; if (bg & TB_HI_BLACK) cbg = 0; break; case TB_OUTPUT_216: cfg = fg & 0xff; cbg = bg & 0xff; if (cfg > 216) cfg = 216; if (cbg > 216) cbg = 216; cfg += 0x0f; cbg += 0x0f; break; case TB_OUTPUT_GRAYSCALE: cfg = fg & 0xff; cbg = bg & 0xff; if (cfg > 24) cfg = 24; if (cbg > 24) cbg = 24; cfg += 0xe7; cbg += 0xe7; break; #if TB_OPT_ATTR_W >= 32 case TB_OUTPUT_TRUECOLOR: cfg = fg & 0xffffff; cbg = bg & 0xffffff; if (fg & TB_HI_BLACK) cfg = 0; if (bg & TB_HI_BLACK) cbg = 0; break; #endif } if (fg & TB_BOLD) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_BOLD])); if (fg & TB_BLINK) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_BLINK])); if (fg & TB_UNDERLINE) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_UNDERLINE])); if (fg & TB_ITALIC) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_ITALIC])); if (fg & TB_DIM) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_DIM])); #if TB_OPT_ATTR_W == 64 if (fg & TB_STRIKEOUT) if_err_return(rv, bytebuf_puts(&global.out, TB_HARDCAP_STRIKEOUT)); if (fg & TB_UNDERLINE_2) if_err_return(rv, bytebuf_puts(&global.out, TB_HARDCAP_UNDERLINE_2)); if (fg & TB_OVERLINE) if_err_return(rv, bytebuf_puts(&global.out, TB_HARDCAP_OVERLINE)); if (fg & TB_INVISIBLE) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_INVISIBLE])); #endif if ((fg & TB_REVERSE) || (bg & TB_REVERSE)) if_err_return(rv, bytebuf_puts(&global.out, global.caps[TB_CAP_REVERSE])); int fg_is_default = (fg & 0xff) == 0; int bg_is_default = (bg & 0xff) == 0; if (global.output_mode == TB_OUTPUT_256) { if (fg & TB_HI_BLACK) fg_is_default = 0; if (bg & TB_HI_BLACK) bg_is_default = 0; } #if TB_OPT_ATTR_W >= 32 if (global.output_mode == TB_OUTPUT_TRUECOLOR) { fg_is_default = ((fg & 0xffffff) == 0) && ((fg & TB_HI_BLACK) == 0); bg_is_default = ((bg & 0xffffff) == 0) && ((bg & TB_HI_BLACK) == 0); } #endif if_err_return(rv, send_sgr(cfg, cbg, fg_is_default, bg_is_default)); global.last_fg = fg; global.last_bg = bg; return TB_OK; } static int send_sgr(uint32_t cfg, uint32_t cbg, int fg_is_default, int bg_is_default) { int rv; char nbuf[32]; if (fg_is_default && bg_is_default) { return TB_OK; } switch (global.output_mode) { default: case TB_OUTPUT_NORMAL: send_literal(rv, "\x1b["); if (!fg_is_default) { send_num(rv, nbuf, cfg); if (!bg_is_default) { send_literal(rv, ";"); } } if (!bg_is_default) { send_num(rv, nbuf, cbg); } send_literal(rv, "m"); break; case TB_OUTPUT_256: case TB_OUTPUT_216: case TB_OUTPUT_GRAYSCALE: send_literal(rv, "\x1b["); if (!fg_is_default) { send_literal(rv, "38;5;"); send_num(rv, nbuf, cfg); if (!bg_is_default) { send_literal(rv, ";"); } } if (!bg_is_default) { send_literal(rv, "48;5;"); send_num(rv, nbuf, cbg); } send_literal(rv, "m"); break; #if TB_OPT_ATTR_W >= 32 case TB_OUTPUT_TRUECOLOR: send_literal(rv, "\x1b["); if (!fg_is_default) { send_literal(rv, "38;2;"); send_num(rv, nbuf, (cfg >> 16) & 0xff); send_literal(rv, ";"); send_num(rv, nbuf, (cfg >> 8) & 0xff); send_literal(rv, ";"); send_num(rv, nbuf, cfg & 0xff); if (!bg_is_default) { send_literal(rv, ";"); } } if (!bg_is_default) { send_literal(rv, "48;2;"); send_num(rv, nbuf, (cbg >> 16) & 0xff); send_literal(rv, ";"); send_num(rv, nbuf, (cbg >> 8) & 0xff); send_literal(rv, ";"); send_num(rv, nbuf, cbg & 0xff); } send_literal(rv, "m"); break; #endif } return TB_OK; } static int send_cursor_if(int x, int y) { int rv; char nbuf[32]; if (x < 0 || y < 0) { return TB_OK; } send_literal(rv, "\x1b["); send_num(rv, nbuf, y + 1); send_literal(rv, ";"); send_num(rv, nbuf, x + 1); send_literal(rv, "H"); return TB_OK; } static int send_char(int x, int y, uint32_t ch) { return send_cluster(x, y, &ch, 1); } static int send_cluster(int x, int y, uint32_t *ch, size_t nch) { int rv; char chu8[8]; if (global.last_x != x - 1 || global.last_y != y) { if_err_return(rv, send_cursor_if(x, y)); } global.last_x = x; global.last_y = y; int i; for (i = 0; i < (int)nch; i++) { uint32_t ch32 = *(ch + i); int chu8_len; if (ch32 == 0) { // replace null with space (from termbox 19dbee5) chu8_len = 1; chu8[0] = ' '; } else { chu8_len = tb_utf8_unicode_to_char(chu8, ch32); } if_err_return(rv, bytebuf_nputs(&global.out, chu8, (size_t)chu8_len)); } return TB_OK; } static int convert_num(uint32_t num, char *buf) { int i, l = 0; char ch; do { /* '0' = 48; 48 + num%10 < 58 < MAX_8bitCHAR */ buf[l++] = (char)('0' + (num % 10)); num /= 10; } while (num); for (i = 0; i < l / 2; i++) { ch = buf[i]; buf[i] = buf[l - 1 - i]; buf[l - 1 - i] = ch; } return l; } static int cell_cmp(struct tb_cell *a, struct tb_cell *b) { if (a->ch != b->ch || a->fg != b->fg || a->bg != b->bg) { return 1; } #ifdef TB_OPT_EGC if (a->nech != b->nech) { return 1; } else if (a->nech > 0) { // a->nech == b->nech return memcmp(a->ech, b->ech, a->nech); } #endif return 0; } static int cell_copy(struct tb_cell *dst, struct tb_cell *src) { #ifdef TB_OPT_EGC if (src->nech > 0) { return cell_set(dst, src->ech, src->nech, src->fg, src->bg); } #endif return cell_set(dst, &src->ch, 1, src->fg, src->bg); } static int cell_set(struct tb_cell *cell, uint32_t *ch, size_t nch, uintattr_t fg, uintattr_t bg) { cell->ch = ch ? *ch : 0; cell->fg = fg; cell->bg = bg; #ifdef TB_OPT_EGC if (nch <= 1) { cell->nech = 0; } else { int rv; if_err_return(rv, cell_reserve_ech(cell, nch + 1)); memcpy(cell->ech, ch, sizeof(ch) * nch); cell->ech[nch] = '\0'; cell->nech = nch; } #else (void)nch; (void)cell_reserve_ech; #endif return TB_OK; } static int cell_reserve_ech(struct tb_cell *cell, size_t n) { #ifdef TB_OPT_EGC if (cell->cech >= n) { return TB_OK; } if (!(cell->ech = tb_realloc(cell->ech, n * sizeof(cell->ch)))) { return TB_ERR_MEM; } cell->cech = n; return TB_OK; #else (void)cell; (void)n; return TB_ERR; #endif } static int cell_free(struct tb_cell *cell) { #ifdef TB_OPT_EGC if (cell->ech) { tb_free(cell->ech); } #endif memset(cell, 0, sizeof(*cell)); return TB_OK; } static int cellbuf_init(struct cellbuf_t *c, int w, int h) { c->cells = tb_malloc(sizeof(struct tb_cell) * w * h); if (!c->cells) { return TB_ERR_MEM; } memset(c->cells, 0, sizeof(struct tb_cell) * w * h); c->width = w; c->height = h; return TB_OK; } static int cellbuf_free(struct cellbuf_t *c) { if (c->cells) { int i; for (i = 0; i < c->width * c->height; i++) { cell_free(&c->cells[i]); } tb_free(c->cells); } memset(c, 0, sizeof(*c)); return TB_OK; } static int cellbuf_clear(struct cellbuf_t *c) { int rv, i; uint32_t space = (uint32_t)' '; for (i = 0; i < c->width * c->height; i++) { if_err_return(rv, cell_set(&c->cells[i], &space, 1, global.fg, global.bg)); } return TB_OK; } static int cellbuf_get(struct cellbuf_t *c, int x, int y, struct tb_cell **out) { if (x < 0 || x >= c->width || y < 0 || y >= c->height) { *out = NULL; return TB_ERR_OUT_OF_BOUNDS; } *out = &c->cells[(y * c->width) + x]; return TB_OK; } static int cellbuf_resize(struct cellbuf_t *c, int w, int h) { int rv; int ow = c->width; int oh = c->height; if (ow == w && oh == h) { return TB_OK; } w = w < 1 ? 1 : w; h = h < 1 ? 1 : h; int minw = (w < ow) ? w : ow; int minh = (h < oh) ? h : oh; struct tb_cell *prev = c->cells; if_err_return(rv, cellbuf_init(c, w, h)); if_err_return(rv, cellbuf_clear(c)); int x, y; for (x = 0; x < minw; x++) { for (y = 0; y < minh; y++) { struct tb_cell *src, *dst; src = &prev[(y * ow) + x]; if_err_return(rv, cellbuf_get(c, x, y, &dst)); if_err_return(rv, cell_copy(dst, src)); } } tb_free(prev); return TB_OK; } static int bytebuf_puts(struct bytebuf_t *b, const char *str) { if (!str || strlen(str) <= 0) return TB_OK; // Nothing to do for empty caps return bytebuf_nputs(b, str, (size_t)strlen(str)); } static int bytebuf_nputs(struct bytebuf_t *b, const char *str, size_t nstr) { int rv; if_err_return(rv, bytebuf_reserve(b, b->len + nstr + 1)); memcpy(b->buf + b->len, str, nstr); b->len += nstr; b->buf[b->len] = '\0'; return TB_OK; } static int bytebuf_shift(struct bytebuf_t *b, size_t n) { if (n > b->len) { n = b->len; } size_t nmove = b->len - n; memmove(b->buf, b->buf + n, nmove); b->len -= n; return TB_OK; } static int bytebuf_flush(struct bytebuf_t *b, int fd) { if (b->len <= 0) { return TB_OK; } ssize_t write_rv = write(fd, b->buf, b->len); if (write_rv < 0 || (size_t)write_rv != b->len) { // Note, errno will be 0 on partial write global.last_errno = errno; return TB_ERR; } b->len = 0; return TB_OK; } static int bytebuf_reserve(struct bytebuf_t *b, size_t sz) { if (b->cap >= sz) { return TB_OK; } size_t newcap = b->cap > 0 ? b->cap : 1; while (newcap < sz) { newcap *= 2; } char *newbuf; if (b->buf) { newbuf = tb_realloc(b->buf, newcap); } else { newbuf = tb_malloc(newcap); } if (!newbuf) { return TB_ERR_MEM; } b->buf = newbuf; b->cap = newcap; return TB_OK; } static int bytebuf_free(struct bytebuf_t *b) { if (b->buf) { tb_free(b->buf); } memset(b, 0, sizeof(*b)); return TB_OK; } #endif /* TB_IMPL */
0
repos/ly
repos/ly/src/main.zig
const std = @import("std"); const build_options = @import("build_options"); const builtin = @import("builtin"); const clap = @import("clap"); const ini = @import("zigini"); const auth = @import("auth.zig"); const bigclock = @import("bigclock.zig"); const interop = @import("interop.zig"); const Doom = @import("animations/Doom.zig"); const Matrix = @import("animations/Matrix.zig"); const TerminalBuffer = @import("tui/TerminalBuffer.zig"); const Session = @import("tui/components/Session.zig"); const Text = @import("tui/components/Text.zig"); const InfoLine = @import("tui/components/InfoLine.zig"); const Config = @import("config/Config.zig"); const Lang = @import("config/Lang.zig"); const Save = @import("config/Save.zig"); const migrator = @import("config/migrator.zig"); const SharedError = @import("SharedError.zig"); const utils = @import("tui/utils.zig"); const Ini = ini.Ini; const termbox = interop.termbox; const unistd = interop.unistd; const temporary_allocator = std.heap.page_allocator; var session_pid: std.posix.pid_t = -1; pub fn signalHandler(i: c_int) callconv(.C) void { if (session_pid == 0) return; // Forward signal to session to clean up if (session_pid > 0) { _ = std.c.kill(session_pid, i); var status: c_int = 0; _ = std.c.waitpid(session_pid, &status, 0); } _ = termbox.tb_shutdown(); std.c.exit(i); } pub fn main() !void { var shutdown = false; var restart = false; var shutdown_cmd: []const u8 = undefined; var restart_cmd: []const u8 = undefined; const stderr = std.io.getStdErr().writer(); defer { // If we can't shutdown or restart due to an error, we print it to standard error. If that fails, just bail out if (shutdown) { const shutdown_error = std.process.execv(temporary_allocator, &[_][]const u8{ "/bin/sh", "-c", shutdown_cmd }); stderr.print("error: couldn't shutdown: {any}\n", .{shutdown_error}) catch std.process.exit(1); } else if (restart) { const restart_error = std.process.execv(temporary_allocator, &[_][]const u8{ "/bin/sh", "-c", restart_cmd }); stderr.print("error: couldn't restart: {any}\n", .{restart_error}) catch std.process.exit(1); } else { // The user has quit Ly using Ctrl+C temporary_allocator.free(shutdown_cmd); temporary_allocator.free(restart_cmd); } } var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // to be able to stop the animation after some time var tv_zero: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv_zero, null); var animation_timed_out: bool = false; const allocator = gpa.allocator(); // Load arguments const params = comptime clap.parseParamsComptime( \\-h, --help Shows all commands. \\-v, --version Shows the version of Ly. \\-c, --config <str> Overrides the default configuration path. Example: --config /usr/share/ly ); var diag = clap.Diagnostic{}; var res = clap.parse(clap.Help, &params, clap.parsers.default, .{ .diagnostic = &diag, .allocator = allocator }) catch |err| { diag.report(stderr, err) catch {}; return err; }; defer res.deinit(); var config: Config = undefined; var lang: Lang = undefined; var save: Save = undefined; var config_load_failed = false; if (res.args.help != 0) { try clap.help(stderr, clap.Help, &params, .{}); _ = try stderr.write("Note: if you want to configure Ly, please check the config file, which is located at " ++ build_options.config_directory ++ "/ly/config.ini.\n"); std.process.exit(0); } if (res.args.version != 0) { _ = try stderr.write("Ly version " ++ build_options.version ++ "\n"); std.process.exit(0); } // Load configuration file var config_ini = Ini(Config).init(allocator); defer config_ini.deinit(); var lang_ini = Ini(Lang).init(allocator); defer lang_ini.deinit(); var save_ini = Ini(Save).init(allocator); defer save_ini.deinit(); var save_path: []const u8 = build_options.config_directory ++ "/ly/save.ini"; var save_path_alloc = false; defer { if (save_path_alloc) allocator.free(save_path); } const comment_characters = "#"; if (res.args.config) |s| { const trailing_slash = if (s[s.len - 1] != '/') "/" else ""; const config_path = try std.fmt.allocPrint(allocator, "{s}{s}config.ini", .{ s, trailing_slash }); defer allocator.free(config_path); config = config_ini.readFileToStruct(config_path, comment_characters, migrator.configFieldHandler) catch _config: { config_load_failed = true; break :_config Config{}; }; const lang_path = try std.fmt.allocPrint(allocator, "{s}{s}lang/{s}.ini", .{ s, trailing_slash, config.lang }); defer allocator.free(lang_path); lang = lang_ini.readFileToStruct(lang_path, comment_characters, null) catch Lang{}; if (config.load) { save_path = try std.fmt.allocPrint(allocator, "{s}{s}save.ini", .{ s, trailing_slash }); save_path_alloc = true; var user_buf: [32]u8 = undefined; save = save_ini.readFileToStruct(save_path, comment_characters, null) catch migrator.tryMigrateSaveFile(&user_buf); } migrator.lateConfigFieldHandler(&config.animation); } else { const config_path = build_options.config_directory ++ "/ly/config.ini"; config = config_ini.readFileToStruct(config_path, comment_characters, migrator.configFieldHandler) catch _config: { config_load_failed = true; break :_config Config{}; }; const lang_path = try std.fmt.allocPrint(allocator, "{s}/ly/lang/{s}.ini", .{ build_options.config_directory, config.lang }); defer allocator.free(lang_path); lang = lang_ini.readFileToStruct(lang_path, comment_characters, null) catch Lang{}; if (config.load) { var user_buf: [32]u8 = undefined; save = save_ini.readFileToStruct(save_path, comment_characters, null) catch migrator.tryMigrateSaveFile(&user_buf); } migrator.lateConfigFieldHandler(&config.animation); } // if (migrator.mapped_config_fields) save_migrated_config: { // var file = try std.fs.cwd().createFile(config_path, .{}); // defer file.close(); // const writer = file.writer(); // ini.writeFromStruct(config, writer, null, true, .{}) catch { // break :save_migrated_config; // }; // } // These strings only end up getting freed if the user quits Ly using Ctrl+C, which is fine since in the other cases // we end up shutting down or restarting the system shutdown_cmd = try temporary_allocator.dupe(u8, config.shutdown_cmd); restart_cmd = try temporary_allocator.dupe(u8, config.restart_cmd); // Initialize termbox _ = termbox.tb_init(); defer _ = termbox.tb_shutdown(); const act = std.posix.Sigaction{ .handler = .{ .handler = &signalHandler }, .mask = std.posix.empty_sigset, .flags = 0, }; try std.posix.sigaction(std.posix.SIG.TERM, &act, null); _ = termbox.tb_set_output_mode(termbox.TB_OUTPUT_NORMAL); _ = termbox.tb_clear(); // Needed to reset termbox after auth const tb_termios = try std.posix.tcgetattr(std.posix.STDIN_FILENO); // Initialize terminal buffer const labels_max_length = @max(lang.login.len, lang.password.len); var seed: u64 = undefined; std.crypto.random.bytes(std.mem.asBytes(&seed)); // Get a random seed for the PRNG (used by animations) var prng = std.Random.DefaultPrng.init(seed); const random = prng.random(); var buffer = TerminalBuffer.init(config, labels_max_length, random); // Initialize components var info_line = InfoLine.init(allocator, &buffer); defer info_line.deinit(); if (config_load_failed) { // We can't localize this since the config failed to load so we'd fallback to the default language anyway try info_line.addMessage("unable to parse config file", config.error_bg, config.error_fg); } interop.setNumlock(config.numlock) catch { try info_line.addMessage(lang.err_numlock, config.error_bg, config.error_fg); }; var session = Session.init(allocator, &buffer, lang); defer session.deinit(); session.addEnvironment(.{ .Name = lang.shell }, null, .shell) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }; if (build_options.enable_x11_support) { if (config.xinitrc) |xinitrc| { session.addEnvironment(.{ .Name = lang.xinitrc, .Exec = xinitrc }, null, .xinitrc) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }; } } else { try info_line.addMessage(lang.no_x11_support, config.bg, config.fg); } if (config.initial_info_text) |text| { try info_line.addMessage(text, config.bg, config.fg); } else get_host_name: { // Initialize information line with host name var name_buf: [std.posix.HOST_NAME_MAX]u8 = undefined; const hostname = std.posix.gethostname(&name_buf) catch { try info_line.addMessage(lang.err_hostname, config.error_bg, config.error_fg); break :get_host_name; }; try info_line.addMessage(hostname, config.bg, config.fg); } try session.crawl(config.waylandsessions, .wayland); if (build_options.enable_x11_support) try session.crawl(config.xsessions, .x11); var login = Text.init(allocator, &buffer, false, null); defer login.deinit(); var password = Text.init(allocator, &buffer, true, config.asterisk); defer password.deinit(); var active_input = config.default_input; var insert_mode = !config.vi_mode or config.vi_default_mode == .insert; // Load last saved username and desktop selection, if any if (config.load) { if (save.user) |user| { try login.text.appendSlice(user); login.end = user.len; login.cursor = login.end; active_input = .password; } if (save.session_index) |session_index| { if (session_index < session.label.list.items.len) session.label.current = session_index; } } // Place components on the screen { buffer.drawBoxCenter(!config.hide_borders, config.blank_box); const coordinates = buffer.calculateComponentCoordinates(); info_line.label.position(coordinates.start_x, coordinates.y, coordinates.full_visible_length, null); session.label.position(coordinates.x, coordinates.y + 2, coordinates.visible_length, config.text_in_center); login.position(coordinates.x, coordinates.y + 4, coordinates.visible_length); password.position(coordinates.x, coordinates.y + 6, coordinates.visible_length); switch (active_input) { .info_line => info_line.label.handle(null, insert_mode), .session => session.label.handle(null, insert_mode), .login => login.handle(null, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, .password => password.handle(null, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, } } // Initialize the animation, if any var doom: Doom = undefined; var matrix: Matrix = undefined; switch (config.animation) { .none => {}, .doom => doom = try Doom.init(allocator, &buffer), .matrix => matrix = try Matrix.init(allocator, &buffer, config.cmatrix_fg), } defer { switch (config.animation) { .none => {}, .doom => doom.deinit(), .matrix => matrix.deinit(), } } const animate = config.animation != .none; const shutdown_key = try std.fmt.parseInt(u8, config.shutdown_key[1..], 10); const shutdown_len = try utils.strWidth(lang.shutdown); const restart_key = try std.fmt.parseInt(u8, config.restart_key[1..], 10); const restart_len = try utils.strWidth(lang.restart); const sleep_key = try std.fmt.parseInt(u8, config.sleep_key[1..], 10); const sleep_len = try utils.strWidth(lang.sleep); const brightness_down_key = try std.fmt.parseInt(u8, config.brightness_down_key[1..], 10); const brightness_down_len = try utils.strWidth(lang.brightness_down); const brightness_up_key = try std.fmt.parseInt(u8, config.brightness_up_key[1..], 10); const brightness_up_len = try utils.strWidth(lang.brightness_up); var event: termbox.tb_event = undefined; var run = true; var update = true; var resolution_changed = false; var auth_fails: u64 = 0; // Switch to selected TTY if possible interop.switchTty(config.console_dev, config.tty) catch { try info_line.addMessage(lang.err_console_dev, config.error_bg, config.error_fg); }; while (run) { // If there's no input or there's an animation, a resolution change needs to be checked if (!update or config.animation != .none) { if (!update) std.time.sleep(std.time.ns_per_ms * 100); _ = termbox.tb_present(); // Required to update tb_width(), tb_height() and tb_cell_buffer() const width: usize = @intCast(termbox.tb_width()); const height: usize = @intCast(termbox.tb_height()); if (width != buffer.width or height != buffer.height) { // If it did change, then update the cell buffer, reallocate the current animation's buffers, and force a draw update buffer.width = width; buffer.height = height; buffer.buffer = termbox.tb_cell_buffer(); switch (config.animation) { .none => {}, .doom => doom.realloc() catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, .matrix => matrix.realloc() catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, } update = true; resolution_changed = true; } } if (update) { // If the user entered a wrong password 10 times in a row, play a cascade animation, else update normally if (auth_fails < config.auth_fails) { _ = termbox.tb_clear(); if (!animation_timed_out) { switch (config.animation) { .none => {}, .doom => doom.draw(), .matrix => matrix.draw(), } } if (config.bigclock != .none and buffer.box_height + (bigclock.HEIGHT + 2) * 2 < buffer.height) draw_big_clock: { const format = "%H:%M"; const xo = buffer.width / 2 - @min(buffer.width, (format.len * (bigclock.WIDTH + 1))) / 2; const yo = (buffer.height - buffer.box_height) / 2 - bigclock.HEIGHT - 2; var clock_buf: [format.len + 1:0]u8 = undefined; const clock_str = interop.timeAsString(&clock_buf, format) catch { break :draw_big_clock; }; for (clock_str, 0..) |c, i| { const clock_cell = bigclock.clockCell(animate, c, buffer.fg, buffer.bg, config.bigclock); bigclock.alphaBlit(xo + i * (bigclock.WIDTH + 1), yo, buffer.width, buffer.height, clock_cell); } } buffer.drawBoxCenter(!config.hide_borders, config.blank_box); if (resolution_changed) { const coordinates = buffer.calculateComponentCoordinates(); info_line.label.position(coordinates.start_x, coordinates.y, coordinates.full_visible_length, null); session.label.position(coordinates.x, coordinates.y + 2, coordinates.visible_length, config.text_in_center); login.position(coordinates.x, coordinates.y + 4, coordinates.visible_length); password.position(coordinates.x, coordinates.y + 6, coordinates.visible_length); resolution_changed = false; } switch (active_input) { .info_line => info_line.label.handle(null, insert_mode), .session => session.label.handle(null, insert_mode), .login => login.handle(null, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, .password => password.handle(null, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, } if (config.clock) |clock| draw_clock: { var clock_buf: [32:0]u8 = undefined; const clock_str = interop.timeAsString(&clock_buf, clock) catch { break :draw_clock; }; if (clock_str.len == 0) return error.FormattedTimeEmpty; buffer.drawLabel(clock_str, buffer.width - @min(buffer.width, clock_str.len), 0); } const label_x = buffer.box_x + buffer.margin_box_h; const label_y = buffer.box_y + buffer.margin_box_v; buffer.drawLabel(lang.login, label_x, label_y + 4); buffer.drawLabel(lang.password, label_x, label_y + 6); info_line.label.draw(); if (!config.hide_key_hints) { var length: usize = 0; buffer.drawLabel(config.shutdown_key, length, 0); length += config.shutdown_key.len + 1; buffer.drawLabel(" ", length - 1, 0); buffer.drawLabel(lang.shutdown, length, 0); length += shutdown_len + 1; buffer.drawLabel(config.restart_key, length, 0); length += config.restart_key.len + 1; buffer.drawLabel(" ", length - 1, 0); buffer.drawLabel(lang.restart, length, 0); length += restart_len + 1; if (config.sleep_cmd != null) { buffer.drawLabel(config.sleep_key, length, 0); length += config.sleep_key.len + 1; buffer.drawLabel(" ", length - 1, 0); buffer.drawLabel(lang.sleep, length, 0); length += sleep_len + 1; } buffer.drawLabel(config.brightness_down_key, length, 0); length += config.brightness_down_key.len + 1; buffer.drawLabel(" ", length - 1, 0); buffer.drawLabel(lang.brightness_down, length, 0); length += brightness_down_len + 1; buffer.drawLabel(config.brightness_up_key, length, 0); length += config.brightness_up_key.len + 1; buffer.drawLabel(" ", length - 1, 0); buffer.drawLabel(lang.brightness_up, length, 0); length += brightness_up_len + 1; } if (config.box_title) |title| { buffer.drawConfinedLabel(title, buffer.box_x, buffer.box_y - 1, buffer.box_width); } if (config.vi_mode) { const label_txt = if (insert_mode) lang.insert else lang.normal; buffer.drawLabel(label_txt, buffer.box_x, buffer.box_y + buffer.box_height); } draw_lock_state: { const lock_state = interop.getLockState(config.console_dev) catch { try info_line.addMessage(lang.err_console_dev, config.error_bg, config.error_fg); break :draw_lock_state; }; var lock_state_x = buffer.width - @min(buffer.width, lang.numlock.len); const lock_state_y: usize = if (config.clock != null) 1 else 0; if (lock_state.numlock) buffer.drawLabel(lang.numlock, lock_state_x, lock_state_y); if (lock_state_x >= lang.capslock.len + 1) { lock_state_x -= lang.capslock.len + 1; if (lock_state.capslock) buffer.drawLabel(lang.capslock, lock_state_x, lock_state_y); } } session.label.draw(); login.draw(); password.draw(); } else { std.time.sleep(std.time.ns_per_ms * 10); update = buffer.cascade(); if (!update) { std.time.sleep(std.time.ns_per_s * 7); auth_fails = 0; } } _ = termbox.tb_present(); } var timeout: i32 = -1; // Calculate the maximum timeout based on current animations, or the (big) clock. If there's none, we wait for the event indefinitely instead if (animate and !animation_timed_out) { timeout = config.min_refresh_delta; // check how long we have been running so we can turn off the animation var tv: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv, null); if (config.animation_timeout_sec > 0 and tv.tv_sec - tv_zero.tv_sec > config.animation_timeout_sec) { animation_timed_out = true; switch (config.animation) { .none => {}, .doom => doom.deinit(), .matrix => matrix.deinit(), } } } else if (config.bigclock != .none and config.clock == null) { var tv: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv, null); timeout = @intCast((60 - @rem(tv.tv_sec, 60)) * 1000 - @divTrunc(tv.tv_usec, 1000) + 1); } else if (config.clock != null or auth_fails >= config.auth_fails) { var tv: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv, null); timeout = @intCast(1000 - @divTrunc(tv.tv_usec, 1000) + 1); } const event_error = if (timeout == -1) termbox.tb_poll_event(&event) else termbox.tb_peek_event(&event, timeout); update = timeout != -1; if (event_error < 0 or event.type != termbox.TB_EVENT_KEY) continue; switch (event.key) { termbox.TB_KEY_ESC => { if (config.vi_mode and insert_mode) { insert_mode = false; update = true; } }, termbox.TB_KEY_F12...termbox.TB_KEY_F1 => { const pressed_key = 0xFFFF - event.key + 1; if (pressed_key == shutdown_key) { shutdown = true; run = false; } else if (pressed_key == restart_key) { restart = true; run = false; } else if (pressed_key == sleep_key) { if (config.sleep_cmd) |sleep_cmd| { var sleep = std.process.Child.init(&[_][]const u8{ "/bin/sh", "-c", sleep_cmd }, allocator); _ = sleep.spawnAndWait() catch .{}; } } else if (pressed_key == brightness_down_key) { var brightness = std.process.Child.init(&[_][]const u8{ "/bin/sh", "-c", config.brightness_down_cmd }, allocator); _ = brightness.spawnAndWait() catch .{}; } else if (pressed_key == brightness_up_key) { var brightness = std.process.Child.init(&[_][]const u8{ "/bin/sh", "-c", config.brightness_up_cmd }, allocator); _ = brightness.spawnAndWait() catch .{}; } }, termbox.TB_KEY_CTRL_C => run = false, termbox.TB_KEY_CTRL_U => { if (active_input == .login) { login.clear(); update = true; } else if (active_input == .password) { password.clear(); update = true; } }, termbox.TB_KEY_CTRL_K, termbox.TB_KEY_ARROW_UP => { active_input = switch (active_input) { .session, .info_line => .info_line, .login => .session, .password => .login, }; update = true; }, termbox.TB_KEY_CTRL_J, termbox.TB_KEY_ARROW_DOWN => { active_input = switch (active_input) { .info_line => .session, .session => .login, .login, .password => .password, }; update = true; }, termbox.TB_KEY_TAB => { active_input = switch (active_input) { .info_line => .session, .session => .login, .login => .password, .password => .info_line, }; update = true; }, termbox.TB_KEY_BACK_TAB => { active_input = switch (active_input) { .info_line => .password, .session => .info_line, .login => .session, .password => .login, }; update = true; }, termbox.TB_KEY_ENTER => { try info_line.addMessage(lang.authenticating, config.bg, config.fg); InfoLine.clearRendered(allocator, buffer) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }; info_line.label.draw(); _ = termbox.tb_present(); if (config.save) save_last_settings: { var file = std.fs.cwd().createFile(save_path, .{}) catch break :save_last_settings; defer file.close(); const save_data = Save{ .user = login.text.items, .session_index = session.label.current, }; ini.writeFromStruct(save_data, file.writer(), null, true, .{}) catch break :save_last_settings; // Delete previous save file if it exists if (migrator.maybe_save_file) |path| std.fs.cwd().deleteFile(path) catch {}; } var shared_err = try SharedError.init(); defer shared_err.deinit(); { const login_text = try allocator.dupeZ(u8, login.text.items); defer allocator.free(login_text); const password_text = try allocator.dupeZ(u8, password.text.items); defer allocator.free(password_text); // Give up control on the TTY _ = termbox.tb_shutdown(); session_pid = try std.posix.fork(); if (session_pid == 0) { const current_environment = session.label.list.items[session.label.current]; auth.authenticate(config, current_environment, login_text, password_text) catch |err| { shared_err.writeError(err); std.process.exit(1); }; std.process.exit(0); } _ = std.posix.waitpid(session_pid, 0); session_pid = -1; } // Take back control of the TTY _ = termbox.tb_init(); _ = termbox.tb_set_output_mode(termbox.TB_OUTPUT_NORMAL); const auth_err = shared_err.readError(); if (auth_err) |err| { auth_fails += 1; active_input = .password; try info_line.addMessage(getAuthErrorMsg(err, lang), config.error_bg, config.error_fg); if (config.clear_password or err != error.PamAuthError) password.clear(); } else { if (config.logout_cmd) |logout_cmd| { var logout_process = std.process.Child.init(&[_][]const u8{ "/bin/sh", "-c", logout_cmd }, allocator); _ = logout_process.spawnAndWait() catch .{}; } password.clear(); try info_line.addMessage(lang.logout, config.bg, config.fg); } try std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, tb_termios); if (auth_fails < config.auth_fails) _ = termbox.tb_clear(); update = true; // Restore the cursor _ = termbox.tb_set_cursor(0, 0); _ = termbox.tb_present(); }, else => { if (!insert_mode) { switch (event.ch) { 'k' => { active_input = switch (active_input) { .session, .info_line => .info_line, .login => .session, .password => .login, }; update = true; continue; }, 'j' => { active_input = switch (active_input) { .info_line => .session, .session => .login, .login, .password => .password, }; update = true; continue; }, 'i' => { insert_mode = true; update = true; continue; }, else => {}, } } switch (active_input) { .info_line => info_line.label.handle(&event, insert_mode), .session => session.label.handle(&event, insert_mode), .login => login.handle(&event, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, .password => password.handle(&event, insert_mode) catch { try info_line.addMessage(lang.err_alloc, config.error_bg, config.error_fg); }, } update = true; }, } } } fn getAuthErrorMsg(err: anyerror, lang: Lang) []const u8 { return switch (err) { error.GetPasswordNameFailed => lang.err_pwnam, error.GetEnvListFailed => lang.err_envlist, error.XauthFailed => lang.err_xauth, error.XcbConnectionFailed => lang.err_xcb_conn, error.GroupInitializationFailed => lang.err_user_init, error.SetUserGidFailed => lang.err_user_gid, error.SetUserUidFailed => lang.err_user_uid, error.ChangeDirectoryFailed => lang.err_perm_dir, error.SetPathFailed => lang.err_path, error.PamAccountExpired => lang.err_pam_acct_expired, error.PamAuthError => lang.err_pam_auth, error.PamAuthInfoUnavailable => lang.err_pam_authinfo_unavail, error.PamBufferError => lang.err_pam_buf, error.PamCredentialsError => lang.err_pam_cred_err, error.PamCredentialsExpired => lang.err_pam_cred_expired, error.PamCredentialsInsufficient => lang.err_pam_cred_insufficient, error.PamCredentialsUnavailable => lang.err_pam_cred_unavail, error.PamMaximumTries => lang.err_pam_maxtries, error.PamNewAuthTokenRequired => lang.err_pam_authok_reqd, error.PamPermissionDenied => lang.err_pam_perm_denied, error.PamSessionError => lang.err_pam_session, error.PamSystemError => lang.err_pam_sys, error.PamUserUnknown => lang.err_pam_user_unknown, error.PamAbort => lang.err_pam_abort, else => lang.err_unknown, }; }
0
repos/ly
repos/ly/src/interop.zig
const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; pub const termbox = @import("termbox2"); pub const pam = @cImport({ @cInclude("security/pam_appl.h"); }); pub const utmp = @cImport({ @cInclude("utmpx.h"); }); // Exists for X11 support only pub const xcb = @cImport({ @cInclude("xcb/xcb.h"); }); pub const unistd = @cImport({ @cInclude("unistd.h"); }); pub const time = @cImport({ @cInclude("time.h"); }); pub const system_time = @cImport({ @cInclude("sys/time.h"); }); pub const stdlib = @cImport({ @cInclude("stdlib.h"); }); pub const pwd = @cImport({ @cInclude("pwd.h"); // We include a FreeBSD-specific header here since login_cap.h references // the passwd struct directly, so we can't import it separately' if (builtin.os.tag == .freebsd) @cInclude("login_cap.h"); }); pub const grp = @cImport({ @cInclude("grp.h"); }); // BSD-specific headers pub const kbio = @cImport({ @cInclude("sys/kbio.h"); }); // Linux-specific headers pub const kd = @cImport({ @cInclude("sys/kd.h"); }); pub const vt = @cImport({ @cInclude("sys/vt.h"); }); // Used for getting & setting the lock state const LedState = if (builtin.os.tag.isBSD()) c_int else c_char; const get_led_state = if (builtin.os.tag.isBSD()) kbio.KDGETLED else kd.KDGKBLED; const set_led_state = if (builtin.os.tag.isBSD()) kbio.KDSETLED else kd.KDSKBLED; const numlock_led = if (builtin.os.tag.isBSD()) kbio.LED_NUM else kd.K_NUMLOCK; const capslock_led = if (builtin.os.tag.isBSD()) kbio.LED_CAP else kd.K_CAPSLOCK; pub fn timeAsString(buf: [:0]u8, format: [:0]const u8) ![]u8 { const timer = std.time.timestamp(); const tm_info = time.localtime(&timer); const len = time.strftime(buf, buf.len, format, tm_info); if (len < 0) return error.CannotGetFormattedTime; return buf[0..len]; } pub fn switchTty(console_dev: []const u8, tty: u8) !void { const fd = try std.posix.open(console_dev, .{ .ACCMODE = .WRONLY }, 0); defer std.posix.close(fd); _ = std.c.ioctl(fd, vt.VT_ACTIVATE, tty); _ = std.c.ioctl(fd, vt.VT_WAITACTIVE, tty); } pub fn getLockState(console_dev: []const u8) !struct { numlock: bool, capslock: bool, } { const fd = try std.posix.open(console_dev, .{ .ACCMODE = .RDONLY }, 0); defer std.posix.close(fd); var led: LedState = undefined; _ = std.c.ioctl(fd, get_led_state, &led); return .{ .numlock = (led & numlock_led) != 0, .capslock = (led & capslock_led) != 0, }; } pub fn setNumlock(val: bool) !void { var led: LedState = undefined; _ = std.c.ioctl(0, get_led_state, &led); const numlock = (led & numlock_led) != 0; if (numlock != val) { const status = std.c.ioctl(std.posix.STDIN_FILENO, set_led_state, led ^ numlock_led); if (status != 0) return error.FailedToSetNumlock; } }
0
repos/ly
repos/ly/src/auth.zig
const std = @import("std"); const build_options = @import("build_options"); const builtin = @import("builtin"); const enums = @import("enums.zig"); const interop = @import("interop.zig"); const TerminalBuffer = @import("tui/TerminalBuffer.zig"); const Session = @import("tui/components/Session.zig"); const Text = @import("tui/components/Text.zig"); const Config = @import("config/Config.zig"); const Allocator = std.mem.Allocator; const Md5 = std.crypto.hash.Md5; const utmp = interop.utmp; const Utmp = utmp.utmpx; const SharedError = @import("SharedError.zig"); var xorg_pid: std.posix.pid_t = 0; pub fn xorgSignalHandler(i: c_int) callconv(.C) void { if (xorg_pid > 0) _ = std.c.kill(xorg_pid, i); } var child_pid: std.posix.pid_t = 0; pub fn sessionSignalHandler(i: c_int) callconv(.C) void { if (child_pid > 0) _ = std.c.kill(child_pid, i); } pub fn authenticate(config: Config, current_environment: Session.Environment, login: [:0]const u8, password: [:0]const u8) !void { var tty_buffer: [3]u8 = undefined; const tty_str = try std.fmt.bufPrintZ(&tty_buffer, "{d}", .{config.tty}); var pam_tty_buffer: [6]u8 = undefined; const pam_tty_str = try std.fmt.bufPrintZ(&pam_tty_buffer, "tty{d}", .{config.tty}); // Set the XDG environment variables setXdgSessionEnv(current_environment.display_server); try setXdgEnv(tty_str, current_environment.xdg_session_desktop orelse "", current_environment.xdg_desktop_names orelse ""); // Open the PAM session var credentials = [_:null]?[*:0]const u8{ login, password }; const conv = interop.pam.pam_conv{ .conv = loginConv, .appdata_ptr = @ptrCast(&credentials), }; var handle: ?*interop.pam.pam_handle = undefined; var status = interop.pam.pam_start(config.service_name, null, &conv, &handle); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); defer _ = interop.pam.pam_end(handle, status); // Set PAM_TTY as the current TTY. This is required in case it isn't being set by another PAM module status = interop.pam.pam_set_item(handle, interop.pam.PAM_TTY, pam_tty_str.ptr); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); // Do the PAM routine status = interop.pam.pam_authenticate(handle, 0); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); status = interop.pam.pam_acct_mgmt(handle, 0); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); status = interop.pam.pam_setcred(handle, interop.pam.PAM_ESTABLISH_CRED); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); defer status = interop.pam.pam_setcred(handle, interop.pam.PAM_DELETE_CRED); status = interop.pam.pam_open_session(handle, 0); if (status != interop.pam.PAM_SUCCESS) return pamDiagnose(status); defer status = interop.pam.pam_close_session(handle, 0); var pwd: *interop.pwd.passwd = undefined; { defer interop.pwd.endpwent(); // Get password structure from username pwd = interop.pwd.getpwnam(login) orelse return error.GetPasswordNameFailed; } // Set user shell if it hasn't already been set if (pwd.pw_shell == null) { interop.unistd.setusershell(); pwd.pw_shell = interop.unistd.getusershell(); interop.unistd.endusershell(); } var shared_err = try SharedError.init(); defer shared_err.deinit(); child_pid = try std.posix.fork(); if (child_pid == 0) { startSession(config, pwd, handle, current_environment) catch |e| { shared_err.writeError(e); std.process.exit(1); }; std.process.exit(0); } var entry = std.mem.zeroes(Utmp); { // If an error occurs here, we can send SIGTERM to the session errdefer cleanup: { _ = std.posix.kill(child_pid, std.posix.SIG.TERM) catch break :cleanup; _ = std.posix.waitpid(child_pid, 0); } // If we receive SIGTERM, forward it to child_pid const act = std.posix.Sigaction{ .handler = .{ .handler = &sessionSignalHandler }, .mask = std.posix.empty_sigset, .flags = 0, }; try std.posix.sigaction(std.posix.SIG.TERM, &act, null); try addUtmpEntry(&entry, pwd.pw_name.?, child_pid); } // Wait for the session to stop _ = std.posix.waitpid(child_pid, 0); removeUtmpEntry(&entry); if (shared_err.readError()) |err| return err; } fn startSession( config: Config, pwd: *interop.pwd.passwd, handle: ?*interop.pam.pam_handle, current_environment: Session.Environment, ) !void { if (builtin.os.tag == .freebsd) { // FreeBSD has initgroups() in unistd const status = interop.unistd.initgroups(pwd.pw_name, pwd.pw_gid); if (status != 0) return error.GroupInitializationFailed; // FreeBSD sets the GID and UID with setusercontext() const result = interop.pwd.setusercontext(null, pwd, pwd.pw_uid, interop.pwd.LOGIN_SETALL); if (result != 0) return error.SetUserUidFailed; } else { const status = interop.grp.initgroups(pwd.pw_name, pwd.pw_gid); if (status != 0) return error.GroupInitializationFailed; std.posix.setgid(pwd.pw_gid) catch return error.SetUserGidFailed; std.posix.setuid(pwd.pw_uid) catch return error.SetUserUidFailed; } // Set up the environment try initEnv(pwd, config.path); // Set the PAM variables const pam_env_vars: ?[*:null]?[*:0]u8 = interop.pam.pam_getenvlist(handle); if (pam_env_vars == null) return error.GetEnvListFailed; const env_list = std.mem.span(pam_env_vars.?); for (env_list) |env_var| _ = interop.stdlib.putenv(env_var); // Change to the user's home directory std.posix.chdirZ(pwd.pw_dir.?) catch return error.ChangeDirectoryFailed; // Execute what the user requested switch (current_environment.display_server) { .wayland => try executeWaylandCmd(pwd.pw_shell.?, config, current_environment.cmd), .shell => try executeShellCmd(pwd.pw_shell.?, config), .xinitrc, .x11 => if (build_options.enable_x11_support) { var vt_buf: [5]u8 = undefined; const vt = try std.fmt.bufPrint(&vt_buf, "vt{d}", .{config.tty}); try executeX11Cmd(pwd.pw_shell.?, pwd.pw_dir.?, config, current_environment.cmd, vt); }, } } fn initEnv(pwd: *interop.pwd.passwd, path_env: ?[:0]const u8) !void { _ = interop.stdlib.setenv("HOME", pwd.pw_dir, 1); _ = interop.stdlib.setenv("PWD", pwd.pw_dir, 1); _ = interop.stdlib.setenv("SHELL", pwd.pw_shell, 1); _ = interop.stdlib.setenv("USER", pwd.pw_name, 1); _ = interop.stdlib.setenv("LOGNAME", pwd.pw_name, 1); if (path_env) |path| { const status = interop.stdlib.setenv("PATH", path, 1); if (status != 0) return error.SetPathFailed; } } fn setXdgSessionEnv(display_server: enums.DisplayServer) void { _ = interop.stdlib.setenv("XDG_SESSION_TYPE", switch (display_server) { .wayland => "wayland", .shell => "tty", .xinitrc, .x11 => "x11", }, 0); } fn setXdgEnv(tty_str: [:0]u8, desktop_name: [:0]const u8, xdg_desktop_names: [:0]const u8) !void { // The "/run/user/%d" directory is not available on FreeBSD. It is much // better to stick to the defaults and let applications using // XDG_RUNTIME_DIR to fall back to directories inside user's home // directory. if (builtin.os.tag != .freebsd) { const uid = interop.unistd.getuid(); var uid_buffer: [10 + @sizeOf(u32) + 1]u8 = undefined; const uid_str = try std.fmt.bufPrintZ(&uid_buffer, "/run/user/{d}", .{uid}); _ = interop.stdlib.setenv("XDG_RUNTIME_DIR", uid_str, 0); } _ = interop.stdlib.setenv("XDG_CURRENT_DESKTOP", xdg_desktop_names, 0); _ = interop.stdlib.setenv("XDG_SESSION_CLASS", "user", 0); _ = interop.stdlib.setenv("XDG_SESSION_ID", "1", 0); _ = interop.stdlib.setenv("XDG_SESSION_DESKTOP", desktop_name, 0); _ = interop.stdlib.setenv("XDG_SEAT", "seat0", 0); _ = interop.stdlib.setenv("XDG_VTNR", tty_str, 0); } fn loginConv( num_msg: c_int, msg: ?[*]?*const interop.pam.pam_message, resp: ?*?[*]interop.pam.pam_response, appdata_ptr: ?*anyopaque, ) callconv(.C) c_int { const message_count: u32 = @intCast(num_msg); const messages = msg.?; const allocator = std.heap.c_allocator; const response = allocator.alloc(interop.pam.pam_response, message_count) catch return interop.pam.PAM_BUF_ERR; // Initialise allocated memory to 0 // This ensures memory can be freed by pam on success @memset(response, std.mem.zeroes(interop.pam.pam_response)); var username: ?[:0]u8 = null; var password: ?[:0]u8 = null; var status: c_int = interop.pam.PAM_SUCCESS; for (0..message_count) |i| set_credentials: { switch (messages[i].?.msg_style) { interop.pam.PAM_PROMPT_ECHO_ON => { const data: [*][*:0]u8 = @ptrCast(@alignCast(appdata_ptr)); username = allocator.dupeZ(u8, std.mem.span(data[0])) catch { status = interop.pam.PAM_BUF_ERR; break :set_credentials; }; response[i].resp = username.?; }, interop.pam.PAM_PROMPT_ECHO_OFF => { const data: [*][*:0]u8 = @ptrCast(@alignCast(appdata_ptr)); password = allocator.dupeZ(u8, std.mem.span(data[1])) catch { status = interop.pam.PAM_BUF_ERR; break :set_credentials; }; response[i].resp = password.?; }, interop.pam.PAM_ERROR_MSG => { status = interop.pam.PAM_CONV_ERR; break :set_credentials; }, else => {}, } } if (status != interop.pam.PAM_SUCCESS) { // Memory is freed by pam otherwise allocator.free(response); if (username != null) allocator.free(username.?); if (password != null) allocator.free(password.?); } else { resp.?.* = response.ptr; } return status; } fn getFreeDisplay() !u8 { var buf: [15]u8 = undefined; var i: u8 = 0; while (i < 200) : (i += 1) { const xlock = try std.fmt.bufPrint(&buf, "/tmp/.X{d}-lock", .{i}); std.posix.access(xlock, std.posix.F_OK) catch break; } return i; } fn getXPid(display_num: u8) !i32 { var buf: [15]u8 = undefined; const file_name = try std.fmt.bufPrint(&buf, "/tmp/.X{d}-lock", .{display_num}); const file = try std.fs.openFileAbsolute(file_name, .{}); defer file.close(); var file_buf: [20]u8 = undefined; var fbs = std.io.fixedBufferStream(&file_buf); _ = try file.reader().streamUntilDelimiter(fbs.writer(), '\n', 20); const line = fbs.getWritten(); return std.fmt.parseInt(i32, std.mem.trim(u8, line, " "), 10); } fn createXauthFile(pwd: [:0]const u8) ![:0]const u8 { var xauth_buf: [100]u8 = undefined; var xauth_dir: [:0]const u8 = undefined; const xdg_rt_dir = std.posix.getenv("XDG_RUNTIME_DIR"); var xauth_file: []const u8 = "lyxauth"; if (xdg_rt_dir == null) { const xdg_cfg_home = std.posix.getenv("XDG_CONFIG_HOME"); var sb: std.c.Stat = undefined; if (xdg_cfg_home == null) { xauth_dir = try std.fmt.bufPrintZ(&xauth_buf, "{s}/.config", .{pwd}); _ = std.c.stat(xauth_dir, &sb); const mode = sb.mode & std.posix.S.IFMT; if (mode == std.posix.S.IFDIR) { xauth_dir = try std.fmt.bufPrintZ(&xauth_buf, "{s}/ly", .{xauth_dir}); } else { xauth_dir = pwd; xauth_file = ".lyxauth"; } } else { xauth_dir = try std.fmt.bufPrintZ(&xauth_buf, "{s}/ly", .{xdg_cfg_home.?}); } _ = std.c.stat(xauth_dir, &sb); const mode = sb.mode & std.posix.S.IFMT; if (mode != std.posix.S.IFDIR) { std.posix.mkdir(xauth_dir, 777) catch { xauth_dir = pwd; xauth_file = ".lyxauth"; }; } } else { xauth_dir = xdg_rt_dir.?; } // Trim trailing slashes var i = xauth_dir.len - 1; while (xauth_dir[i] == '/') i -= 1; const trimmed_xauth_dir = xauth_dir[0 .. i + 1]; var buf: [256]u8 = undefined; const xauthority: [:0]u8 = try std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ trimmed_xauth_dir, xauth_file }); const file = try std.fs.createFileAbsoluteZ(xauthority, .{}); file.close(); return xauthority; } fn mcookie() [Md5.digest_length * 2]u8 { var buf: [4096]u8 = undefined; std.crypto.random.bytes(&buf); var out: [Md5.digest_length]u8 = undefined; Md5.hash(&buf, &out, .{}); return std.fmt.bytesToHex(&out, .lower); } fn xauth(display_name: [:0]u8, shell: [*:0]const u8, pw_dir: [*:0]const u8, config: Config) !void { var pwd_buf: [100]u8 = undefined; const pwd = try std.fmt.bufPrintZ(&pwd_buf, "{s}", .{pw_dir}); const xauthority = try createXauthFile(pwd); _ = interop.stdlib.setenv("XAUTHORITY", xauthority, 1); _ = interop.stdlib.setenv("DISPLAY", display_name, 1); const magic_cookie = mcookie(); const pid = try std.posix.fork(); if (pid == 0) { const log_file = try redirectStandardStreams(config.session_log, true); defer log_file.close(); var cmd_buffer: [1024]u8 = undefined; const cmd_str = std.fmt.bufPrintZ(&cmd_buffer, "{s} add {s} . {s}", .{ config.xauth_cmd, display_name, magic_cookie }) catch std.process.exit(1); const args = [_:null]?[*:0]const u8{ shell, "-c", cmd_str }; std.posix.execveZ(shell, &args, std.c.environ) catch {}; std.process.exit(1); } const status = std.posix.waitpid(pid, 0); if (status.status != 0) return error.XauthFailed; } fn executeShellCmd(shell: [*:0]const u8, config: Config) !void { // We don't want to redirect stdout and stderr in a shell session var cmd_buffer: [1024]u8 = undefined; const cmd_str = try std.fmt.bufPrintZ(&cmd_buffer, "{s} {s} {s}", .{ config.setup_cmd, config.login_cmd orelse "", shell }); const args = [_:null]?[*:0]const u8{ shell, "-c", cmd_str }; return std.posix.execveZ(shell, &args, std.c.environ); } fn executeWaylandCmd(shell: [*:0]const u8, config: Config, desktop_cmd: []const u8) !void { const log_file = try redirectStandardStreams(config.session_log, true); defer log_file.close(); var cmd_buffer: [1024]u8 = undefined; const cmd_str = try std.fmt.bufPrintZ(&cmd_buffer, "{s} {s} {s}", .{ config.setup_cmd, config.login_cmd orelse "", desktop_cmd }); const args = [_:null]?[*:0]const u8{ shell, "-c", cmd_str }; return std.posix.execveZ(shell, &args, std.c.environ); } fn executeX11Cmd(shell: [*:0]const u8, pw_dir: [*:0]const u8, config: Config, desktop_cmd: []const u8, vt: []const u8) !void { const display_num = try getFreeDisplay(); var buf: [5]u8 = undefined; const display_name = try std.fmt.bufPrintZ(&buf, ":{d}", .{display_num}); try xauth(display_name, shell, pw_dir, config); const pid = try std.posix.fork(); if (pid == 0) { var cmd_buffer: [1024]u8 = undefined; const cmd_str = std.fmt.bufPrintZ(&cmd_buffer, "{s} {s} {s} >{s} 2>&1", .{ config.x_cmd, display_name, vt, config.session_log }) catch std.process.exit(1); const args = [_:null]?[*:0]const u8{ shell, "-c", cmd_str }; std.posix.execveZ(shell, &args, std.c.environ) catch {}; std.process.exit(1); } var ok: c_int = undefined; var xcb: ?*interop.xcb.xcb_connection_t = null; while (ok != 0) { xcb = interop.xcb.xcb_connect(null, null); ok = interop.xcb.xcb_connection_has_error(xcb); std.posix.kill(pid, 0) catch |e| { if (e == error.ProcessNotFound and ok != 0) return error.XcbConnectionFailed; }; } // X Server detaches from the process. // PID can be fetched from /tmp/X{d}.lock const x_pid = try getXPid(display_num); xorg_pid = try std.posix.fork(); if (xorg_pid == 0) { var cmd_buffer: [1024]u8 = undefined; const cmd_str = std.fmt.bufPrintZ(&cmd_buffer, "{s} {s} {s} >{s} 2>&1", .{ config.setup_cmd, config.login_cmd orelse "", desktop_cmd, config.session_log }) catch std.process.exit(1); const args = [_:null]?[*:0]const u8{ shell, "-c", cmd_str }; std.posix.execveZ(shell, &args, std.c.environ) catch {}; std.process.exit(1); } // If we receive SIGTERM, clean up by killing the xorg_pid process const act = std.posix.Sigaction{ .handler = .{ .handler = &xorgSignalHandler }, .mask = std.posix.empty_sigset, .flags = 0, }; try std.posix.sigaction(std.posix.SIG.TERM, &act, null); _ = std.posix.waitpid(xorg_pid, 0); interop.xcb.xcb_disconnect(xcb); std.posix.kill(x_pid, 0) catch return; std.posix.kill(x_pid, std.posix.SIG.TERM) catch {}; var status: c_int = 0; _ = std.c.waitpid(x_pid, &status, 0); } fn redirectStandardStreams(session_log: []const u8, create: bool) !std.fs.File { const log_file = if (create) (try std.fs.cwd().createFile(session_log, .{ .mode = 0o666 })) else (try std.fs.cwd().openFile(session_log, .{ .mode = .read_write })); try std.posix.dup2(std.posix.STDOUT_FILENO, std.posix.STDERR_FILENO); try std.posix.dup2(log_file.handle, std.posix.STDOUT_FILENO); return log_file; } fn addUtmpEntry(entry: *Utmp, username: [*:0]const u8, pid: c_int) !void { entry.ut_type = utmp.USER_PROCESS; entry.ut_pid = pid; var buf: [4096]u8 = undefined; const ttyname = try std.os.getFdPath(std.posix.STDIN_FILENO, &buf); var ttyname_buf: [@sizeOf(@TypeOf(entry.ut_line))]u8 = undefined; _ = try std.fmt.bufPrintZ(&ttyname_buf, "{s}", .{ttyname["/dev/".len..]}); entry.ut_line = ttyname_buf; entry.ut_id = ttyname_buf["tty".len..7].*; var username_buf: [@sizeOf(@TypeOf(entry.ut_user))]u8 = undefined; _ = try std.fmt.bufPrintZ(&username_buf, "{s}", .{username}); entry.ut_user = username_buf; var host: [@sizeOf(@TypeOf(entry.ut_host))]u8 = undefined; host[0] = 0; entry.ut_host = host; var tv: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv, null); entry.ut_tv = .{ .tv_sec = @intCast(tv.tv_sec), .tv_usec = @intCast(tv.tv_usec), }; entry.ut_addr_v6[0] = 0; utmp.setutxent(); _ = utmp.pututxline(entry); utmp.endutxent(); } fn removeUtmpEntry(entry: *Utmp) void { entry.ut_type = utmp.DEAD_PROCESS; entry.ut_line[0] = 0; entry.ut_user[0] = 0; utmp.setutxent(); _ = utmp.pututxline(entry); utmp.endutxent(); } fn pamDiagnose(status: c_int) anyerror { return switch (status) { interop.pam.PAM_ACCT_EXPIRED => return error.PamAccountExpired, interop.pam.PAM_AUTH_ERR => return error.PamAuthError, interop.pam.PAM_AUTHINFO_UNAVAIL => return error.PamAuthInfoUnavailable, interop.pam.PAM_BUF_ERR => return error.PamBufferError, interop.pam.PAM_CRED_ERR => return error.PamCredentialsError, interop.pam.PAM_CRED_EXPIRED => return error.PamCredentialsExpired, interop.pam.PAM_CRED_INSUFFICIENT => return error.PamCredentialsInsufficient, interop.pam.PAM_CRED_UNAVAIL => return error.PamCredentialsUnavailable, interop.pam.PAM_MAXTRIES => return error.PamMaximumTries, interop.pam.PAM_NEW_AUTHTOK_REQD => return error.PamNewAuthTokenRequired, interop.pam.PAM_PERM_DENIED => return error.PamPermissionDenied, interop.pam.PAM_SESSION_ERR => return error.PamSessionError, interop.pam.PAM_SYSTEM_ERR => return error.PamSystemError, interop.pam.PAM_USER_UNKNOWN => return error.PamUserUnknown, else => return error.PamAbort, }; }
0
repos/ly
repos/ly/src/SharedError.zig
const std = @import("std"); const ErrInt = std.meta.Int(.unsigned, @bitSizeOf(anyerror)); const ErrorHandler = packed struct { has_error: bool = false, err_int: ErrInt = 0, }; const SharedError = @This(); data: []align(std.mem.page_size) u8, pub fn init() !SharedError { const data = try std.posix.mmap(null, @sizeOf(ErrorHandler), std.posix.PROT.READ | std.posix.PROT.WRITE, .{ .TYPE = .SHARED, .ANONYMOUS = true }, -1, 0); return .{ .data = data }; } pub fn deinit(self: *SharedError) void { std.posix.munmap(self.data); } pub fn writeError(self: SharedError, err: anyerror) void { var buf_stream = std.io.fixedBufferStream(self.data); const writer = buf_stream.writer(); writer.writeStruct(ErrorHandler{ .has_error = true, .err_int = @intFromError(err) }) catch {}; } pub fn readError(self: SharedError) ?anyerror { var buf_stream = std.io.fixedBufferStream(self.data); const reader = buf_stream.reader(); const err_handler = try reader.readStruct(ErrorHandler); if (err_handler.has_error) return @errorFromInt(err_handler.err_int); return null; }
0
repos/ly
repos/ly/src/enums.zig
pub const Animation = enum { none, doom, matrix, }; pub const DisplayServer = enum { wayland, shell, xinitrc, x11, }; pub const Input = enum { info_line, session, login, password, }; pub const ViMode = enum { normal, insert, }; pub const Bigclock = enum { none, en, fa, };
0
repos/ly
repos/ly/src/bigclock.zig
const std = @import("std"); const interop = @import("interop.zig"); const utils = @import("tui/utils.zig"); const enums = @import("enums.zig"); const Lang = @import("bigclock/Lang.zig"); const en = @import("bigclock/en.zig"); const fa = @import("bigclock/fa.zig"); const termbox = interop.termbox; const Bigclock = enums.Bigclock; pub const WIDTH = Lang.WIDTH; pub const HEIGHT = Lang.HEIGHT; pub const SIZE = Lang.SIZE; pub fn clockCell(animate: bool, char: u8, fg: u16, bg: u16, bigclock: Bigclock) [SIZE]utils.Cell { var cells: [SIZE]utils.Cell = undefined; var tv: interop.system_time.timeval = undefined; _ = interop.system_time.gettimeofday(&tv, null); const clock_chars = toBigNumber(if (animate and char == ':' and @divTrunc(tv.tv_usec, 500000) != 0) ' ' else char, bigclock); for (0..cells.len) |i| cells[i] = utils.initCell(clock_chars[i], fg, bg); return cells; } pub fn alphaBlit(x: usize, y: usize, tb_width: usize, tb_height: usize, cells: [SIZE]utils.Cell) void { if (x + WIDTH >= tb_width or y + HEIGHT >= tb_height) return; for (0..HEIGHT) |yy| { for (0..WIDTH) |xx| { const cell = cells[yy * WIDTH + xx]; if (cell.ch != 0) utils.putCell(x + xx, y + yy, cell); } } } fn toBigNumber(char: u8, bigclock: Bigclock) []const u21 { const locale_chars = switch (bigclock) { .fa => fa.locale_chars, .en => en.locale_chars, .none => unreachable, }; return switch (char) { '0' => &locale_chars.ZERO, '1' => &locale_chars.ONE, '2' => &locale_chars.TWO, '3' => &locale_chars.THREE, '4' => &locale_chars.FOUR, '5' => &locale_chars.FIVE, '6' => &locale_chars.SIX, '7' => &locale_chars.SEVEN, '8' => &locale_chars.EIGHT, '9' => &locale_chars.NINE, ':' => &locale_chars.S, else => &locale_chars.E, }; }
0
repos/ly/src
repos/ly/src/tui/utils.zig
const std = @import("std"); const interop = @import("../interop.zig"); const termbox = interop.termbox; pub const Cell = struct { ch: u32, fg: u16, bg: u16, }; pub fn initCell(ch: u32, fg: u16, bg: u16) Cell { return .{ .ch = ch, .fg = fg, .bg = bg, }; } pub fn putCell(x: usize, y: usize, cell: Cell) void { _ = termbox.tb_set_cell(@intCast(x), @intCast(y), cell.ch, cell.fg, cell.bg); } // Every codepoint is assumed to have a width of 1. // Since ly should be running in a tty, this should be fine. pub fn strWidth(str: []const u8) !u8 { const utf8view = try std.unicode.Utf8View.init(str); var utf8 = utf8view.iterator(); var i: u8 = 0; while (utf8.nextCodepoint()) |_| i += 1; return i; }
0
repos/ly/src
repos/ly/src/tui/TerminalBuffer.zig
const std = @import("std"); const builtin = @import("builtin"); const interop = @import("../interop.zig"); const utils = @import("utils.zig"); const Config = @import("../config/Config.zig"); const Random = std.Random; const termbox = interop.termbox; const TerminalBuffer = @This(); random: Random, width: usize, height: usize, buffer: [*]termbox.tb_cell, fg: u16, bg: u16, border_fg: u16, box_chars: struct { left_up: u32, left_down: u32, right_up: u32, right_down: u32, top: u32, bottom: u32, left: u32, right: u32, }, labels_max_length: usize, box_x: usize, box_y: usize, box_width: usize, box_height: usize, margin_box_v: u8, margin_box_h: u8, pub fn init(config: Config, labels_max_length: usize, random: Random) TerminalBuffer { return .{ .random = random, .width = @intCast(termbox.tb_width()), .height = @intCast(termbox.tb_height()), .buffer = termbox.tb_cell_buffer(), .fg = config.fg, .bg = config.bg, .border_fg = config.border_fg, .box_chars = if (builtin.os.tag == .linux or builtin.os.tag.isBSD()) .{ .left_up = 0x250C, .left_down = 0x2514, .right_up = 0x2510, .right_down = 0x2518, .top = 0x2500, .bottom = 0x2500, .left = 0x2502, .right = 0x2502, } else .{ .left_up = '+', .left_down = '+', .right_up = '+', .right_down = '+', .top = '-', .bottom = '-', .left = '|', .right = '|', }, .labels_max_length = labels_max_length, .box_x = 0, .box_y = 0, .box_width = (2 * config.margin_box_h) + config.input_len + 1 + labels_max_length, .box_height = 7 + (2 * config.margin_box_v), .margin_box_v = config.margin_box_v, .margin_box_h = config.margin_box_h, }; } pub fn cascade(self: TerminalBuffer) bool { var changed = false; var y = self.height - 2; while (y > 0) : (y -= 1) { for (0..self.width) |x| { const cell = self.buffer[(y - 1) * self.width + x]; const cell_under = self.buffer[y * self.width + x]; const char: u8 = @truncate(cell.ch); if (std.ascii.isWhitespace(char)) continue; const char_under: u8 = @truncate(cell_under.ch); if (!std.ascii.isWhitespace(char_under)) continue; changed = true; if ((self.random.int(u16) % 10) > 7) continue; _ = termbox.tb_set_cell(@intCast(x), @intCast(y), cell.ch, cell.fg, cell.bg); _ = termbox.tb_set_cell(@intCast(x), @intCast(y - 1), ' ', cell_under.fg, cell_under.bg); } } return changed; } pub fn drawBoxCenter(self: *TerminalBuffer, show_borders: bool, blank_box: bool) void { if (self.width < 2 or self.height < 2) return; const x1 = (self.width - @min(self.width - 2, self.box_width)) / 2; const y1 = (self.height - @min(self.height - 2, self.box_height)) / 2; const x2 = (self.width + @min(self.width, self.box_width)) / 2; const y2 = (self.height + @min(self.height, self.box_height)) / 2; self.box_x = x1; self.box_y = y1; if (show_borders) { _ = termbox.tb_set_cell(@intCast(x1 - 1), @intCast(y1 - 1), self.box_chars.left_up, self.border_fg, self.bg); _ = termbox.tb_set_cell(@intCast(x2), @intCast(y1 - 1), self.box_chars.right_up, self.border_fg, self.bg); _ = termbox.tb_set_cell(@intCast(x1 - 1), @intCast(y2), self.box_chars.left_down, self.border_fg, self.bg); _ = termbox.tb_set_cell(@intCast(x2), @intCast(y2), self.box_chars.right_down, self.border_fg, self.bg); var c1 = utils.initCell(self.box_chars.top, self.border_fg, self.bg); var c2 = utils.initCell(self.box_chars.bottom, self.border_fg, self.bg); for (0..self.box_width) |i| { utils.putCell(x1 + i, y1 - 1, c1); utils.putCell(x1 + i, y2, c2); } c1.ch = self.box_chars.left; c2.ch = self.box_chars.right; for (0..self.box_height) |i| { utils.putCell(x1 - 1, y1 + i, c1); utils.putCell(x2, y1 + i, c2); } } if (blank_box) { const blank = utils.initCell(' ', self.fg, self.bg); for (0..self.box_height) |y| { for (0..self.box_width) |x| { utils.putCell(x1 + x, y1 + y, blank); } } } } pub fn calculateComponentCoordinates(self: TerminalBuffer) struct { start_x: usize, x: usize, y: usize, full_visible_length: usize, visible_length: usize, } { const start_x = self.box_x + self.margin_box_h; const x = start_x + self.labels_max_length + 1; const y = self.box_y + self.margin_box_v; const full_visible_length = self.box_x + self.box_width - self.margin_box_h - start_x; const visible_length = self.box_x + self.box_width - self.margin_box_h - x; return .{ .start_x = start_x, .x = x, .y = y, .full_visible_length = full_visible_length, .visible_length = visible_length, }; } pub fn drawLabel(self: TerminalBuffer, text: []const u8, x: usize, y: usize) void { drawColorLabel(text, x, y, self.fg, self.bg); } pub fn drawColorLabel(text: []const u8, x: usize, y: usize, fg: u16, bg: u16) void { const yc: c_int = @intCast(y); const utf8view = std.unicode.Utf8View.init(text) catch return; var utf8 = utf8view.iterator(); var i = x; while (utf8.nextCodepoint()) |codepoint| : (i += 1) { _ = termbox.tb_set_cell(@intCast(i), yc, codepoint, fg, bg); } } pub fn drawConfinedLabel(self: TerminalBuffer, text: []const u8, x: usize, y: usize, max_length: usize) void { const yc: c_int = @intCast(y); const utf8view = std.unicode.Utf8View.init(text) catch return; var utf8 = utf8view.iterator(); var i: usize = 0; while (utf8.nextCodepoint()) |codepoint| : (i += 1) { if (i >= max_length) break; _ = termbox.tb_set_cell(@intCast(i + x), yc, codepoint, self.fg, self.bg); } } pub fn drawCharMultiple(self: TerminalBuffer, char: u8, x: usize, y: usize, length: usize) void { const cell = utils.initCell(char, self.fg, self.bg); for (0..length) |xx| utils.putCell(x + xx, y, cell); }
0
repos/ly/src/tui
repos/ly/src/tui/components/InfoLine.zig
const std = @import("std"); const TerminalBuffer = @import("../TerminalBuffer.zig"); const generic = @import("generic.zig"); const utils = @import("../utils.zig"); const Allocator = std.mem.Allocator; const MessageLabel = generic.CyclableLabel(Message); const InfoLine = @This(); const Message = struct { width: u8, text: []const u8, bg: u16, fg: u16, }; label: MessageLabel, pub fn init(allocator: Allocator, buffer: *TerminalBuffer) InfoLine { return .{ .label = MessageLabel.init(allocator, buffer, drawItem), }; } pub fn deinit(self: InfoLine) void { self.label.deinit(); } pub fn addMessage(self: *InfoLine, text: []const u8, bg: u16, fg: u16) !void { if (text.len == 0) return; try self.label.addItem(.{ .width = try utils.strWidth(text), .text = text, .bg = bg, .fg = fg, }); } pub fn clearRendered(allocator: Allocator, buffer: TerminalBuffer) !void { // Draw over the area const y = buffer.box_y + buffer.margin_box_v; const spaces = try allocator.alloc(u8, buffer.box_width); defer allocator.free(spaces); @memset(spaces, ' '); buffer.drawLabel(spaces, buffer.box_x, y); } fn drawItem(label: *MessageLabel, message: Message, _: usize, _: usize) bool { if (message.width == 0 or label.buffer.box_width <= message.width) return false; const x = label.buffer.box_x + ((label.buffer.box_width - message.width) / 2); label.first_char_x = x + message.width; TerminalBuffer.drawColorLabel(message.text, x, label.y, message.fg, message.bg); return true; }
0
repos/ly/src/tui
repos/ly/src/tui/components/Text.zig
const std = @import("std"); const interop = @import("../../interop.zig"); const TerminalBuffer = @import("../TerminalBuffer.zig"); const utils = @import("../utils.zig"); const Allocator = std.mem.Allocator; const DynamicString = std.ArrayList(u8); const termbox = interop.termbox; const Text = @This(); allocator: Allocator, buffer: *TerminalBuffer, text: DynamicString, end: usize, cursor: usize, visible_start: usize, visible_length: usize, x: usize, y: usize, masked: bool, maybe_mask: ?u8, pub fn init(allocator: Allocator, buffer: *TerminalBuffer, masked: bool, maybe_mask: ?u8) Text { const text = DynamicString.init(allocator); return .{ .allocator = allocator, .buffer = buffer, .text = text, .end = 0, .cursor = 0, .visible_start = 0, .visible_length = 0, .x = 0, .y = 0, .masked = masked, .maybe_mask = maybe_mask, }; } pub fn deinit(self: Text) void { self.text.deinit(); } pub fn position(self: *Text, x: usize, y: usize, visible_length: usize) void { self.x = x; self.y = y; self.visible_length = visible_length; } pub fn handle(self: *Text, maybe_event: ?*termbox.tb_event, insert_mode: bool) !void { if (maybe_event) |event| blk: { if (event.type != termbox.TB_EVENT_KEY) break :blk; switch (event.key) { termbox.TB_KEY_ARROW_LEFT => self.goLeft(), termbox.TB_KEY_ARROW_RIGHT => self.goRight(), termbox.TB_KEY_DELETE => self.delete(), termbox.TB_KEY_BACKSPACE, termbox.TB_KEY_BACKSPACE2 => { if (insert_mode) { self.backspace(); } else { self.goLeft(); } }, termbox.TB_KEY_SPACE => try self.write(' '), else => { if (event.ch > 31 and event.ch < 127) { if (insert_mode) { try self.write(@intCast(event.ch)); } else { switch (event.ch) { 'h' => self.goLeft(), 'l' => self.goRight(), else => {}, } } } }, } } if (self.masked and self.maybe_mask == null) { _ = termbox.tb_set_cursor(@intCast(self.x), @intCast(self.y)); return; } _ = termbox.tb_set_cursor(@intCast(self.x + (self.cursor - self.visible_start)), @intCast(self.y)); } pub fn draw(self: Text) void { if (self.masked) { if (self.maybe_mask) |mask| { const length = @min(self.text.items.len, self.visible_length - 1); if (length == 0) return; self.buffer.drawCharMultiple(mask, self.x, self.y, length); } return; } const length = @min(self.text.items.len, self.visible_length); if (length == 0) return; const visible_slice = vs: { if (self.text.items.len > self.visible_length and self.cursor < self.text.items.len) { break :vs self.text.items[self.visible_start..(self.visible_length + self.visible_start)]; } else { break :vs self.text.items[self.visible_start..]; } }; self.buffer.drawLabel(visible_slice, self.x, self.y); } pub fn clear(self: *Text) void { self.text.clearRetainingCapacity(); self.end = 0; self.cursor = 0; self.visible_start = 0; } fn goLeft(self: *Text) void { if (self.cursor == 0) return; if (self.visible_start > 0) self.visible_start -= 1; self.cursor -= 1; } fn goRight(self: *Text) void { if (self.cursor >= self.end) return; if (self.cursor - self.visible_start == self.visible_length - 1) self.visible_start += 1; self.cursor += 1; } fn delete(self: *Text) void { if (self.cursor >= self.end) return; _ = self.text.orderedRemove(self.cursor); self.end -= 1; } fn backspace(self: *Text) void { if (self.cursor == 0) return; self.goLeft(); self.delete(); } fn write(self: *Text, char: u8) !void { if (char == 0) return; try self.text.insert(self.cursor, char); self.end += 1; self.goRight(); }
0
repos/ly/src/tui
repos/ly/src/tui/components/Session.zig
const std = @import("std"); const TerminalBuffer = @import("../TerminalBuffer.zig"); const enums = @import("../../enums.zig"); const generic = @import("generic.zig"); const Ini = @import("zigini").Ini; const Lang = @import("../../config/Lang.zig"); const Allocator = std.mem.Allocator; const DisplayServer = enums.DisplayServer; const EnvironmentLabel = generic.CyclableLabel(Environment); const Session = @This(); pub const Environment = struct { entry_ini: ?Ini(Entry) = null, name: [:0]const u8 = "", xdg_session_desktop: ?[:0]const u8 = null, xdg_desktop_names: ?[:0]const u8 = null, cmd: []const u8 = "", specifier: []const u8 = "", display_server: DisplayServer = .wayland, }; const DesktopEntry = struct { Exec: []const u8 = "", Name: [:0]const u8 = "", DesktopNames: ?[:0]u8 = null, }; pub const Entry = struct { @"Desktop Entry": DesktopEntry = .{} }; label: EnvironmentLabel, lang: Lang, pub fn init(allocator: Allocator, buffer: *TerminalBuffer, lang: Lang) Session { return .{ .label = EnvironmentLabel.init(allocator, buffer, drawItem), .lang = lang, }; } pub fn deinit(self: Session) void { for (self.label.list.items) |*environment| { if (environment.entry_ini) |*entry_ini| entry_ini.deinit(); if (environment.xdg_session_desktop) |session_desktop| self.label.allocator.free(session_desktop); } self.label.deinit(); } pub fn addEnvironment(self: *Session, entry: DesktopEntry, xdg_session_desktop: ?[:0]const u8, display_server: DisplayServer) !void { var xdg_desktop_names: ?[:0]const u8 = null; if (entry.DesktopNames) |desktop_names| { for (desktop_names) |*c| { if (c.* == ';') c.* = ':'; } xdg_desktop_names = desktop_names; } try self.label.addItem(.{ .entry_ini = null, .name = entry.Name, .xdg_session_desktop = xdg_session_desktop, .xdg_desktop_names = xdg_desktop_names, .cmd = entry.Exec, .specifier = switch (display_server) { .wayland => self.lang.wayland, .x11 => self.lang.x11, else => self.lang.other, }, .display_server = display_server, }); } pub fn addEnvironmentWithIni(self: *Session, entry_ini: Ini(Entry), xdg_session_desktop: ?[:0]const u8, display_server: DisplayServer) !void { const entry = entry_ini.data.@"Desktop Entry"; var xdg_desktop_names: ?[:0]const u8 = null; if (entry.DesktopNames) |desktop_names| { for (desktop_names) |*c| { if (c.* == ';') c.* = ':'; } xdg_desktop_names = desktop_names; } try self.label.addItem(.{ .entry_ini = entry_ini, .name = entry.Name, .xdg_session_desktop = xdg_session_desktop, .xdg_desktop_names = xdg_desktop_names, .cmd = entry.Exec, .specifier = switch (display_server) { .wayland => self.lang.wayland, .x11 => self.lang.x11, else => self.lang.other, }, .display_server = display_server, }); } pub fn crawl(self: *Session, path: []const u8, display_server: DisplayServer) !void { var iterable_directory = std.fs.openDirAbsolute(path, .{ .iterate = true }) catch return; defer iterable_directory.close(); var iterator = iterable_directory.iterate(); while (try iterator.next()) |item| { if (!std.mem.eql(u8, std.fs.path.extension(item.name), ".desktop")) continue; const entry_path = try std.fmt.allocPrint(self.label.allocator, "{s}/{s}", .{ path, item.name }); defer self.label.allocator.free(entry_path); var entry_ini = Ini(Entry).init(self.label.allocator); _ = try entry_ini.readFileToStruct(entry_path, "#", null); errdefer entry_ini.deinit(); var xdg_session_desktop: []const u8 = undefined; const maybe_desktop_names = entry_ini.data.@"Desktop Entry".DesktopNames; if (maybe_desktop_names) |desktop_names| { xdg_session_desktop = std.mem.sliceTo(desktop_names, ';'); } else { // if DesktopNames is empty, we'll take the name of the session file xdg_session_desktop = std.fs.path.stem(item.name); } const session_desktop = try self.label.allocator.dupeZ(u8, xdg_session_desktop); errdefer self.label.allocator.free(session_desktop); try self.addEnvironmentWithIni(entry_ini, session_desktop, display_server); } } fn drawItem(label: *EnvironmentLabel, environment: Environment, x: usize, y: usize) bool { const length = @min(environment.name.len, label.visible_length - 3); if (length == 0) return false; const nx = if (label.text_in_center) (label.x + (label.visible_length - environment.name.len) / 2) else (label.x + 2); label.first_char_x = nx + environment.name.len; label.buffer.drawLabel(environment.specifier, x, y); label.buffer.drawLabel(environment.name, nx, label.y); return true; }
0
repos/ly/src/tui
repos/ly/src/tui/components/generic.zig
const std = @import("std"); const enums = @import("../../enums.zig"); const interop = @import("../../interop.zig"); const TerminalBuffer = @import("../TerminalBuffer.zig"); pub fn CyclableLabel(comptime ItemType: type) type { return struct { const Allocator = std.mem.Allocator; const ItemList = std.ArrayList(ItemType); const DrawItemFn = *const fn (*Self, ItemType, usize, usize) bool; const termbox = interop.termbox; const Self = @This(); allocator: Allocator, buffer: *TerminalBuffer, list: ItemList, current: usize, visible_length: usize, x: usize, y: usize, first_char_x: usize, text_in_center: bool, draw_item_fn: DrawItemFn, pub fn init(allocator: Allocator, buffer: *TerminalBuffer, draw_item_fn: DrawItemFn) Self { return .{ .allocator = allocator, .buffer = buffer, .list = ItemList.init(allocator), .current = 0, .visible_length = 0, .x = 0, .y = 0, .first_char_x = 0, .text_in_center = false, .draw_item_fn = draw_item_fn, }; } pub fn deinit(self: Self) void { self.list.deinit(); } pub fn position(self: *Self, x: usize, y: usize, visible_length: usize, text_in_center: ?bool) void { self.x = x; self.y = y; self.visible_length = visible_length; self.first_char_x = x + 2; if (text_in_center) |value| { self.text_in_center = value; } } pub fn addItem(self: *Self, item: ItemType) !void { try self.list.append(item); self.current = self.list.items.len - 1; } pub fn handle(self: *Self, maybe_event: ?*termbox.tb_event, insert_mode: bool) void { if (maybe_event) |event| blk: { if (event.type != termbox.TB_EVENT_KEY) break :blk; switch (event.key) { termbox.TB_KEY_ARROW_LEFT, termbox.TB_KEY_CTRL_H => self.goLeft(), termbox.TB_KEY_ARROW_RIGHT, termbox.TB_KEY_CTRL_L => self.goRight(), else => { if (!insert_mode) { switch (event.ch) { 'h' => self.goLeft(), 'l' => self.goRight(), else => {}, } } }, } } _ = termbox.tb_set_cursor(@intCast(self.first_char_x), @intCast(self.y)); } pub fn draw(self: *Self) void { if (self.list.items.len == 0) return; const current_item = self.list.items[self.current]; const x = self.buffer.box_x + self.buffer.margin_box_h; const y = self.buffer.box_y + self.buffer.margin_box_v + 2; const continue_drawing = @call(.auto, self.draw_item_fn, .{ self, current_item, x, y }); if (!continue_drawing) return; _ = termbox.tb_set_cell(@intCast(self.x), @intCast(self.y), '<', self.buffer.fg, self.buffer.bg); _ = termbox.tb_set_cell(@intCast(self.x + self.visible_length - 1), @intCast(self.y), '>', self.buffer.fg, self.buffer.bg); } fn goLeft(self: *Self) void { if (self.current == 0) { self.current = self.list.items.len - 1; return; } self.current -= 1; } fn goRight(self: *Self) void { if (self.current == self.list.items.len - 1) { self.current = 0; return; } self.current += 1; } }; }
0
repos/ly/src
repos/ly/src/animations/Doom.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const TerminalBuffer = @import("../tui/TerminalBuffer.zig"); const utils = @import("../tui/utils.zig"); const interop = @import("../interop.zig"); const termbox = interop.termbox; const Doom = @This(); pub const STEPS = 13; pub const FIRE = [_]utils.Cell{ utils.initCell(' ', 9, 0), utils.initCell(0x2591, 2, 0), // Red utils.initCell(0x2592, 2, 0), // Red utils.initCell(0x2593, 2, 0), // Red utils.initCell(0x2588, 2, 0), // Red utils.initCell(0x2591, 4, 2), // Yellow utils.initCell(0x2592, 4, 2), // Yellow utils.initCell(0x2593, 4, 2), // Yellow utils.initCell(0x2588, 4, 2), // Yellow utils.initCell(0x2591, 8, 4), // White utils.initCell(0x2592, 8, 4), // White utils.initCell(0x2593, 8, 4), // White utils.initCell(0x2588, 8, 4), // White }; allocator: Allocator, terminal_buffer: *TerminalBuffer, buffer: []u8, pub fn init(allocator: Allocator, terminal_buffer: *TerminalBuffer) !Doom { const buffer = try allocator.alloc(u8, terminal_buffer.width * terminal_buffer.height); initBuffer(buffer, terminal_buffer.width); return .{ .allocator = allocator, .terminal_buffer = terminal_buffer, .buffer = buffer, }; } pub fn deinit(self: Doom) void { self.allocator.free(self.buffer); } pub fn realloc(self: *Doom) !void { const buffer = try self.allocator.realloc(self.buffer, self.terminal_buffer.width * self.terminal_buffer.height); initBuffer(buffer, self.terminal_buffer.width); self.buffer = buffer; } pub fn draw(self: Doom) void { for (0..self.terminal_buffer.width) |x| { for (1..self.terminal_buffer.height) |y| { const source = y * self.terminal_buffer.width + x; const random = (self.terminal_buffer.random.int(u16) % 7) & 3; var dest = (source - @min(source, random)) + 1; if (self.terminal_buffer.width > dest) dest = 0 else dest -= self.terminal_buffer.width; const buffer_source = self.buffer[source]; const buffer_dest_offset = random & 1; if (buffer_source < buffer_dest_offset) continue; var buffer_dest = buffer_source - buffer_dest_offset; if (buffer_dest > 12) buffer_dest = 0; self.buffer[dest] = @intCast(buffer_dest); self.terminal_buffer.buffer[dest] = toTermboxCell(FIRE[buffer_dest]); self.terminal_buffer.buffer[source] = toTermboxCell(FIRE[buffer_source]); } } } fn initBuffer(buffer: []u8, width: usize) void { const length = buffer.len - width; const slice_start = buffer[0..length]; const slice_end = buffer[length..]; @memset(slice_start, 0); @memset(slice_end, STEPS - 1); } fn toTermboxCell(cell: utils.Cell) termbox.tb_cell { return .{ .ch = cell.ch, .fg = cell.fg, .bg = cell.bg, }; }
0
repos/ly/src
repos/ly/src/animations/Matrix.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Random = std.rand.Random; const TerminalBuffer = @import("../tui/TerminalBuffer.zig"); const interop = @import("../interop.zig"); const termbox = interop.termbox; pub const FRAME_DELAY: u64 = 8; // Allowed codepoints pub const MIN_CODEPOINT: isize = 33; pub const MAX_CODEPOINT: isize = 123 - MIN_CODEPOINT; // Characters change mid-scroll pub const MID_SCROLL_CHANGE = true; const Matrix = @This(); pub const Dot = struct { value: isize, is_head: bool, }; pub const Line = struct { space: isize, length: isize, update: isize, }; allocator: Allocator, terminal_buffer: *TerminalBuffer, dots: []Dot, lines: []Line, frame: u64, count: u64, fg_ini: u16, pub fn init(allocator: Allocator, terminal_buffer: *TerminalBuffer, fg_ini: u16) !Matrix { const dots = try allocator.alloc(Dot, terminal_buffer.width * (terminal_buffer.height + 1)); const lines = try allocator.alloc(Line, terminal_buffer.width); initBuffers(dots, lines, terminal_buffer.width, terminal_buffer.height, terminal_buffer.random); return .{ .allocator = allocator, .terminal_buffer = terminal_buffer, .dots = dots, .lines = lines, .frame = 3, .count = 0, .fg_ini = fg_ini, }; } pub fn deinit(self: Matrix) void { self.allocator.free(self.dots); self.allocator.free(self.lines); } pub fn realloc(self: *Matrix) !void { const dots = try self.allocator.realloc(self.dots, self.terminal_buffer.width * (self.terminal_buffer.height + 1)); const lines = try self.allocator.realloc(self.lines, self.terminal_buffer.width); initBuffers(dots, lines, self.terminal_buffer.width, self.terminal_buffer.height, self.terminal_buffer.random); self.dots = dots; self.lines = lines; } pub fn draw(self: *Matrix) void { const buf_height = self.terminal_buffer.height; const buf_width = self.terminal_buffer.width; self.count += 1; if (self.count > FRAME_DELAY) { self.frame += 1; if (self.frame > 4) self.frame = 1; self.count = 0; var x: usize = 0; while (x < self.terminal_buffer.width) : (x += 2) { var tail: usize = 0; var line = &self.lines[x]; if (self.frame <= line.update) continue; if (self.dots[x].value == -1 and self.dots[self.terminal_buffer.width + x].value == ' ') { if (line.space > 0) { line.space -= 1; } else { const randint = self.terminal_buffer.random.int(i16); const h: isize = @intCast(self.terminal_buffer.height); line.length = @mod(randint, h - 3) + 3; self.dots[x].value = @mod(randint, MAX_CODEPOINT) + MIN_CODEPOINT; line.space = @mod(randint, h + 1); } } var y: usize = 0; var first_col = true; var seg_len: u64 = 0; height_it: while (y <= buf_height) : (y += 1) { var dot = &self.dots[buf_width * y + x]; // Skip over spaces while (y <= buf_height and (dot.value == ' ' or dot.value == -1)) { y += 1; if (y > buf_height) break :height_it; dot = &self.dots[buf_width * y + x]; } // Find the head of this column tail = y; seg_len = 0; while (y <= buf_height and dot.value != ' ' and dot.value != -1) { dot.is_head = false; if (MID_SCROLL_CHANGE) { const randint = self.terminal_buffer.random.int(i16); if (@mod(randint, 8) == 0) { dot.value = @mod(randint, MAX_CODEPOINT) + MIN_CODEPOINT; } } y += 1; seg_len += 1; // Head's down offscreen if (y > buf_height) { self.dots[buf_width * tail + x].value = ' '; break :height_it; } dot = &self.dots[buf_width * y + x]; } const randint = self.terminal_buffer.random.int(i16); dot.value = @mod(randint, MAX_CODEPOINT) + MIN_CODEPOINT; dot.is_head = true; if (seg_len > line.length or !first_col) { self.dots[buf_width * tail + x].value = ' '; self.dots[x].value = -1; } first_col = false; } } } var x: usize = 0; while (x < buf_width) : (x += 2) { var y: usize = 1; while (y <= self.terminal_buffer.height) : (y += 1) { const dot = self.dots[buf_width * y + x]; var fg = self.fg_ini; if (dot.value == -1 or dot.value == ' ') { _ = termbox.tb_set_cell(@intCast(x), @intCast(y - 1), ' ', fg, termbox.TB_DEFAULT); continue; } if (dot.is_head) fg = @intCast(termbox.TB_WHITE | termbox.TB_BOLD); _ = termbox.tb_set_cell(@intCast(x), @intCast(y - 1), @intCast(dot.value), fg, termbox.TB_DEFAULT); } } } fn initBuffers(dots: []Dot, lines: []Line, width: usize, height: usize, random: Random) void { var y: usize = 0; while (y <= height) : (y += 1) { var x: usize = 0; while (x < width) : (x += 2) { dots[y * width + x].value = -1; } } var x: usize = 0; while (x < width) : (x += 2) { var line = lines[x]; const h: isize = @intCast(height); line.space = @mod(random.int(i16), h) + 1; line.length = @mod(random.int(i16), h - 3) + 3; line.update = @mod(random.int(i16), 3) + 1; lines[x] = line; dots[width + x].value = ' '; } }
0
repos/ly/src
repos/ly/src/config/migrator.zig
// The migrator ensures compatibility with <=0.6.0 configuration files const std = @import("std"); const ini = @import("zigini"); const Save = @import("Save.zig"); const enums = @import("../enums.zig"); var temporary_allocator = std.heap.page_allocator; pub var maybe_animate: ?bool = null; pub var maybe_save_file: ?[]const u8 = null; pub var mapped_config_fields = false; pub fn configFieldHandler(_: std.mem.Allocator, field: ini.IniField) ?ini.IniField { if (std.mem.eql(u8, field.key, "animate")) { // The option doesn't exist anymore, but we save its value for "animation" maybe_animate = std.mem.eql(u8, field.value, "true"); mapped_config_fields = true; return null; } if (std.mem.eql(u8, field.key, "animation")) { // The option now uses a string (which then gets converted into an enum) instead of an integer // It also combines the previous "animate" and "animation" options const animation = std.fmt.parseInt(u8, field.value, 10) catch return field; var mapped_field = field; mapped_field.value = switch (animation) { 0 => "doom", 1 => "matrix", else => "none", }; mapped_config_fields = true; return mapped_field; } if (std.mem.eql(u8, field.key, "blank_password")) { // The option has simply been renamed var mapped_field = field; mapped_field.key = "clear_password"; mapped_config_fields = true; return mapped_field; } if (std.mem.eql(u8, field.key, "default_input")) { // The option now uses a string (which then gets converted into an enum) instead of an integer const default_input = std.fmt.parseInt(u8, field.value, 10) catch return field; var mapped_field = field; mapped_field.value = switch (default_input) { 0 => "session", 1 => "login", 2 => "password", else => "login", }; mapped_config_fields = true; return mapped_field; } if (std.mem.eql(u8, field.key, "save_file")) { // The option doesn't exist anymore, but we save its value for migration later on maybe_save_file = temporary_allocator.dupe(u8, field.value) catch return null; mapped_config_fields = true; return null; } if (std.mem.eql(u8, field.key, "wayland_specifier") or std.mem.eql(u8, field.key, "max_desktop_len") or std.mem.eql(u8, field.key, "max_login_len") or std.mem.eql(u8, field.key, "max_password_len") or std.mem.eql(u8, field.key, "mcookie_cmd") or std.mem.eql(u8, field.key, "term_reset_cmd") or std.mem.eql(u8, field.key, "term_restore_cursor_cmd") or std.mem.eql(u8, field.key, "x_cmd_setup") or std.mem.eql(u8, field.key, "wayland_cmd")) { // The options don't exist anymore mapped_config_fields = true; return null; } if (std.mem.eql(u8, field.key, "bigclock")) { // The option now uses a string (which then gets converted into an enum) instead of an boolean // It also includes the ability to change active bigclock's language var mapped_field = field; if (std.mem.eql(u8, field.value, "true")){ mapped_field.value = "en"; mapped_config_fields = true; }else if (std.mem.eql(u8, field.value, "false")){ mapped_field.value = "none"; mapped_config_fields = true; } return mapped_field; } return field; } // This is the stuff we only handle after reading the config. // For example, the "animate" field could come after "animation" pub fn lateConfigFieldHandler(animation: *enums.Animation) void { if (maybe_animate) |animate| { if (!animate) animation.* = .none; } } pub fn tryMigrateSaveFile(user_buf: *[32]u8) Save { var save = Save{}; if (maybe_save_file) |path| { defer temporary_allocator.free(path); var file = std.fs.openFileAbsolute(path, .{}) catch return save; defer file.close(); const reader = file.reader(); var user_fbs = std.io.fixedBufferStream(user_buf); reader.streamUntilDelimiter(user_fbs.writer(), '\n', user_buf.len) catch return save; const user = user_fbs.getWritten(); if (user.len > 0) save.user = user; var session_buf: [20]u8 = undefined; var session_fbs = std.io.fixedBufferStream(&session_buf); reader.streamUntilDelimiter(session_fbs.writer(), '\n', session_buf.len) catch return save; const session_index_str = session_fbs.getWritten(); var session_index: ?usize = null; if (session_index_str.len > 0) { session_index = std.fmt.parseUnsigned(usize, session_index_str, 10) catch return save; } save.session_index = session_index; } return save; }
0
repos/ly/src
repos/ly/src/config/Lang.zig
authenticating: []const u8 = "authenticating...", brightness_down: []const u8 = "decrease brightness", brightness_up: []const u8 = "increase brightness", capslock: []const u8 = "capslock", err_alloc: []const u8 = "failed memory allocation", err_bounds: []const u8 = "out-of-bounds index", err_brightness_change: []const u8 = "failed to change brightness", err_chdir: []const u8 = "failed to open home folder", err_config: []const u8 = "unable to parse config file", err_console_dev: []const u8 = "failed to access console", err_dgn_oob: []const u8 = "log message", err_domain: []const u8 = "invalid domain", err_envlist: []const u8 = "failed to get envlist", err_hostname: []const u8 = "failed to get hostname", err_mlock: []const u8 = "failed to lock password memory", err_null: []const u8 = "null pointer", err_numlock: []const u8 = "failed to set numlock", err_pam: []const u8 = "pam transaction failed", err_pam_abort: []const u8 = "pam transaction aborted", err_pam_acct_expired: []const u8 = "account expired", err_pam_auth: []const u8 = "authentication error", err_pam_authinfo_unavail: []const u8 = "failed to get user info", err_pam_authok_reqd: []const u8 = "token expired", err_pam_buf: []const u8 = "memory buffer error", err_pam_cred_err: []const u8 = "failed to set credentials", err_pam_cred_expired: []const u8 = "credentials expired", err_pam_cred_insufficient: []const u8 = "insufficient credentials", err_pam_cred_unavail: []const u8 = "failed to get credentials", err_pam_maxtries: []const u8 = "reached maximum tries limit", err_pam_perm_denied: []const u8 = "permission denied", err_pam_session: []const u8 = "session error", err_pam_sys: []const u8 = "system error", err_pam_user_unknown: []const u8 = "unknown user", err_path: []const u8 = "failed to set path", err_perm_dir: []const u8 = "failed to change current directory", err_perm_group: []const u8 = "failed to downgrade group permissions", err_perm_user: []const u8 = "failed to downgrade user permissions", err_pwnam: []const u8 = "failed to get user info", err_unknown: []const u8 = "an unknown error occurred", err_user_gid: []const u8 = "failed to set user GID", err_user_init: []const u8 = "failed to initialize user", err_user_uid: []const u8 = "failed to set user UID", err_xauth: []const u8 = "xauth command failed", err_xcb_conn: []const u8 = "xcb connection failed", err_xsessions_dir: []const u8 = "failed to find sessions folder", err_xsessions_open: []const u8 = "failed to open sessions folder", insert: []const u8 = "insert", login: []const u8 = "login:", logout: []const u8 = "logged out", normal: []const u8 = "normal", no_x11_support: []const u8 = "x11 support disabled at compile-time", numlock: []const u8 = "numlock", other: []const u8 = "other", password: []const u8 = "password:", restart: []const u8 = "reboot", shell: [:0]const u8 = "shell", shutdown: []const u8 = "shutdown", sleep: []const u8 = "sleep", wayland: []const u8 = "wayland", xinitrc: [:0]const u8 = "xinitrc", x11: []const u8 = "x11",
0
repos/ly/src
repos/ly/src/config/Save.zig
user: ?[]const u8 = null, session_index: ?usize = null,
0
repos/ly/src
repos/ly/src/config/Config.zig
const build_options = @import("build_options"); const enums = @import("../enums.zig"); const Animation = enums.Animation; const Input = enums.Input; const ViMode = enums.ViMode; const Bigclock = enums.Bigclock; animation: Animation = .none, animation_timeout_sec: u12 = 0, asterisk: ?u8 = '*', auth_fails: u64 = 10, bg: u16 = 0, bigclock: Bigclock = .none, blank_box: bool = true, border_fg: u16 = 8, box_title: ?[]const u8 = null, brightness_down_cmd: [:0]const u8 = build_options.prefix_directory ++ "/bin/brightnessctl -q s 10%-", brightness_down_key: []const u8 = "F5", brightness_up_cmd: [:0]const u8 = build_options.prefix_directory ++ "/bin/brightnessctl -q s +10%", brightness_up_key: []const u8 = "F6", clear_password: bool = false, clock: ?[:0]const u8 = null, cmatrix_fg: u16 = 3, console_dev: []const u8 = "/dev/console", default_input: Input = .login, error_bg: u16 = 0, error_fg: u16 = 258, fg: u16 = 8, hide_borders: bool = false, hide_key_hints: bool = false, initial_info_text: ?[]const u8 = null, input_len: u8 = 34, lang: []const u8 = "en", load: bool = true, login_cmd: ?[]const u8 = null, logout_cmd: ?[]const u8 = null, margin_box_h: u8 = 2, margin_box_v: u8 = 1, min_refresh_delta: u16 = 5, numlock: bool = false, path: ?[:0]const u8 = "/sbin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", restart_cmd: []const u8 = "/sbin/shutdown -r now", restart_key: []const u8 = "F2", save: bool = true, service_name: [:0]const u8 = "ly", session_log: []const u8 = "ly-session.log", setup_cmd: []const u8 = build_options.config_directory ++ "/ly/setup.sh", shutdown_cmd: []const u8 = "/sbin/shutdown -a now", shutdown_key: []const u8 = "F1", sleep_cmd: ?[]const u8 = null, sleep_key: []const u8 = "F3", text_in_center: bool = false, tty: u8 = build_options.tty, vi_default_mode: ViMode = .normal, vi_mode: bool = false, waylandsessions: []const u8 = build_options.prefix_directory ++ "/share/wayland-sessions", x_cmd: []const u8 = build_options.prefix_directory ++ "/bin/X", xauth_cmd: []const u8 = build_options.prefix_directory ++ "/bin/xauth", xinitrc: ?[]const u8 = "~/.xinitrc", xsessions: []const u8 = build_options.prefix_directory ++ "/share/xsessions",
0
repos/ly/src
repos/ly/src/bigclock/en.zig
const Lang = @import("Lang.zig"); const LocaleChars = Lang.LocaleChars; const X = Lang.X; const O = Lang.O; // zig fmt: off pub const locale_chars = LocaleChars{ .ZERO = [_]u21{ X,X,X,X,X, X,X,O,X,X, X,X,O,X,X, X,X,O,X,X, X,X,X,X,X, }, .ONE = [_]u21{ O,O,O,X,X, O,O,O,X,X, O,O,O,X,X, O,O,O,X,X, O,O,O,X,X, }, .TWO = [_]u21{ X,X,X,X,X, O,O,O,X,X, X,X,X,X,X, X,X,O,O,O, X,X,X,X,X, }, .THREE = [_]u21{ X,X,X,X,X, O,O,O,X,X, X,X,X,X,X, O,O,O,X,X, X,X,X,X,X, }, .FOUR = [_]u21{ X,X,O,X,X, X,X,O,X,X, X,X,X,X,X, O,O,O,X,X, O,O,O,X,X, }, .FIVE = [_]u21{ X,X,X,X,X, X,X,O,O,O, X,X,X,X,X, O,O,O,X,X, X,X,X,X,X, }, .SIX = [_]u21{ X,X,X,X,X, X,X,O,O,O, X,X,X,X,X, X,X,O,X,X, X,X,X,X,X, }, .SEVEN = [_]u21{ X,X,X,X,X, O,O,O,X,X, O,O,O,X,X, O,O,O,X,X, O,O,O,X,X, }, .EIGHT = [_]u21{ X,X,X,X,X, X,X,O,X,X, X,X,X,X,X, X,X,O,X,X, X,X,X,X,X, }, .NINE = [_]u21{ X,X,X,X,X, X,X,O,X,X, X,X,X,X,X, O,O,O,X,X, X,X,X,X,X, }, .S = [_]u21{ O,O,O,O,O, O,O,X,O,O, O,O,O,O,O, O,O,X,O,O, O,O,O,O,O, }, .E = [_]u21{ O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, }, }; // zig fmt: on
0
repos/ly/src
repos/ly/src/bigclock/fa.zig
const Lang = @import("Lang.zig"); const LocaleChars = Lang.LocaleChars; const X = Lang.X; const O = Lang.O; // zig fmt: off pub const locale_chars = LocaleChars{ .ZERO = [_]u21{ O,O,O,O,O, O,O,X,O,O, O,X,O,X,O, O,O,X,O,O, O,O,O,O,O, }, .ONE = [_]u21{ O,O,X,O,O, O,X,X,O,O, O,O,X,O,O, O,O,X,O,O, O,O,X,O,O, }, .TWO = [_]u21{ O,X,O,X,O, O,X,X,X,O, O,X,O,O,O, O,X,O,O,O, O,X,O,O,O, }, .THREE = [_]u21{ X,O,X,O,X, X,X,X,X,X, X,O,O,O,O, X,O,O,O,O, X,O,O,O,O, }, .FOUR = [_]u21{ O,X,O,X,X, O,X,X,O,O, O,X,X,X,X, O,X,O,O,O, O,X,O,O,O, }, .FIVE = [_]u21{ O,O,X,X,O, O,X,O,O,X, X,O,O,O,X, X,O,X,O,X, O,X,O,X,O, }, .SIX = [_]u21{ O,X,X,O,O, O,X,O,O,X, O,O,X,O,O, O,X,O,O,O, X,O,O,O,O, }, .SEVEN = [_]u21{ X,O,O,O,X, X,O,O,O,X, O,X,O,X,O, O,X,O,X,O, O,O,X,O,O, }, .EIGHT = [_]u21{ O,O,O,X,O, O,O,X,O,X, O,O,X,O,X, O,X,O,O,X, O,X,O,O,X, }, .NINE = [_]u21{ O,X,X,X,O, O,X,O,X,O, O,X,X,X,O, O,O,O,X,O, O,O,O,X,O, }, .S = [_]u21{ O,O,O,O,O, O,O,X,O,O, O,O,O,O,O, O,O,X,O,O, O,O,O,O,O, }, .E = [_]u21{ O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, O,O,O,O,O, }, }; // zig fmt: on
0
repos/ly/src
repos/ly/src/bigclock/Lang.zig
const builtin = @import("builtin"); pub const WIDTH = 5; pub const HEIGHT = 5; pub const SIZE = WIDTH * HEIGHT; pub const X: u32 = if (builtin.os.tag == .linux or builtin.os.tag.isBSD()) 0x2593 else '#'; pub const O: u32 = 0; pub const LocaleChars = struct { ZERO: [SIZE]u21, ONE: [SIZE]u21, TWO: [SIZE]u21, THREE: [SIZE]u21, FOUR: [SIZE]u21, FIVE: [SIZE]u21, SIX: [SIZE]u21, SEVEN: [SIZE]u21, EIGHT: [SIZE]u21, NINE: [SIZE]u21, S: [SIZE]u21, E: [SIZE]u21, };
0
repos/ly
repos/ly/res/config.ini
# The color settings in Ly take a digit 0-8 corresponding to: #define TB_DEFAULT 0x00 #define TB_BLACK 0x01 #define TB_RED 0x02 #define TB_GREEN 0x03 #define TB_YELLOW 0x04 #define TB_BLUE 0x05 #define TB_MAGENTA 0x06 #define TB_CYAN 0x07 #define TB_WHITE 0x08 # The default color varies, but usually it makes the background black and the foreground white. # You can also combine these colors with the following style attributes using bitwise OR: #define TB_BOLD 0x0100 #define TB_UNDERLINE 0x0200 #define TB_REVERSE 0x0400 #define TB_ITALIC 0x0800 #define TB_BLINK 0x1000 #define TB_HI_BLACK 0x2000 #define TB_BRIGHT 0x4000 #define TB_DIM 0x8000 # For example, to set the foreground color to red and bold, you would do 0x02 | 0x0100 = 0x0102. # Note that you must pre-calculate the value because Ly doesn't parse bitwise OR operations in its config. # # Moreover, to set the VT color palette, you are encouraged to use another tool such as # mkinitcpio-colors (https://github.com/evanpurkhiser/mkinitcpio-colors). Note that the color palette defined with # mkinitcpio-colors takes 16 colors (0-15), only values 0-8 are valid with Ly and these values do not correspond # exactly. For instance, in defining palettes with mkinitcpio-colors, the order is black, dark red, dark green, brown, dark # blue, dark purple, dark cyan, light gray, dark gray, bright red, bright green, yellow, bright blue, bright purple, bright # cyan, and white, indexed in that order 0 through 15. For example, the color defined for white (indexed at 15 in the mkinitcpio # config) will be used by Ly for fg = 0x0008. # The active animation # none -> Nothing # doom -> PSX DOOM fire # matrix -> CMatrix animation = none # Stop the animation after some time # 0 -> Run forever # 1..2e12 -> Stop the animation after this many seconds animation_timeout_sec = 0 # The character used to mask the password # If null, the password will be hidden # Note: you can use a # by escaping it like so: \# asterisk = * # The number of failed authentications before a special animation is played... ;) auth_fails = 10 # Background color id bg = 0x0000 # Change the state and language of the big clock # none -> Disabled (default) # en -> English # fa -> Farsi bigclock = none # Blank main box background # Setting to false will make it transparent blank_box = true # Border foreground color id border_fg = 0x0008 # Title to show at the top of the main box # If set to null, none will be shown box_title = null # Brightness increase command brightness_down_cmd = $PREFIX_DIRECTORY/bin/brightnessctl -q s 10%- # Brightness decrease key brightness_down_key = F5 # Brightness increase command brightness_up_cmd = $PREFIX_DIRECTORY/bin/brightnessctl -q s +10% # Brightness increase key brightness_up_key = F6 # Erase password input on failure clear_password = false # Format string for clock in top right corner (see strftime specification). Example: %c # If null, the clock won't be shown clock = null # CMatrix animation foreground color id cmatrix_fg = 0x0003 # Console path console_dev = /dev/console # Input box active by default on startup # Available inputs: info_line, session, login, password default_input = login # Error background color id error_bg = 0x0000 # Error foreground color id # Default is red and bold: TB_RED | TB_BOLD error_fg = 0x0102 # Foreground color id fg = 0x0008 # Remove main box borders hide_borders = false # Remove power management command hints hide_key_hints = false # Initial text to show on the info line # If set to null, the info line defaults to the hostname initial_info_text = null # Input boxes length input_len = 34 # Active language # Available languages are found in $CONFIG_DIRECTORY/ly/lang/ lang = en # Load the saved desktop and username load = true # Command executed when logging in # If null, no command will be executed # Important: the code itself must end with `exec "$@"` in order to launch the session! # You can also set environment variables in there, they'll persist until logout login_cmd = null # Command executed when logging out # If null, no command will be executed # Important: the session will already be terminated when this command is executed, so # no need to add `exec "$@"` at the end logout_cmd = null # Main box horizontal margin margin_box_h = 2 # Main box vertical margin margin_box_v = 1 # Event timeout in milliseconds min_refresh_delta = 5 # Set numlock on/off at startup numlock = false # Default path # If null, ly doesn't set a path path = /sbin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin # Command executed when pressing restart_key restart_cmd = /sbin/shutdown -r now # Specifies the key used for restart (F1-F12) restart_key = F2 # Save the current desktop and login as defaults save = true # Service name (set to ly to use the provided pam config file) service_name = ly # Session log file path # This will contain stdout and stderr of X11 and Wayland sessions # By default it's saved in the user's home directory # Note: this file won't be used in a shell session (due to the need of stdout and stderr) session_log = ly-session.log # Setup command setup_cmd = $CONFIG_DIRECTORY/ly/setup.sh # Command executed when pressing shutdown_key shutdown_cmd = /sbin/shutdown -a now # Specifies the key used for shutdown (F1-F12) shutdown_key = F1 # Command executed when pressing sleep key (can be null) sleep_cmd = null # Specifies the key used for sleep (F1-F12) sleep_key = F3 # Center the session name. text_in_center = false # TTY in use tty = $DEFAULT_TTY # Default vi mode # normal -> normal mode # insert -> insert mode vi_default_mode = normal # Enable vi keybindings vi_mode = false # Wayland desktop environments waylandsessions = $PREFIX_DIRECTORY/share/wayland-sessions # Xorg server command x_cmd = $PREFIX_DIRECTORY/bin/X # Xorg xauthority edition tool xauth_cmd = $PREFIX_DIRECTORY/bin/xauth # xinitrc # If null, the xinitrc session will be hidden xinitrc = ~/.xinitrc # Xorg desktop environments xsessions = $PREFIX_DIRECTORY/share/xsessions
0
repos/ly
repos/ly/res/valgrind.supp
{ pam Memcheck:Leak ... obj:/usr/lib/libpam.so.0.84.2 ... } { termbox Memcheck:Leak ... fun:tb_init ... } { libc/dynamic Memcheck:Leak ... fun:_dl_catch_exception ... } { libc/groups Memcheck:Leak ... fun:initgroups ... }
0
repos/ly
repos/ly/res/ly.service
[Unit] Description=TUI display manager After=systemd-user-sessions.service plymouth-quit-wait.service After=getty@tty$DEFAULT_TTY.service Conflicts=getty@tty$DEFAULT_TTY.service [Service] Type=idle ExecStart=$PREFIX_DIRECTORY/bin/$EXECUTABLE_NAME StandardInput=tty TTYPath=/dev/tty$DEFAULT_TTY TTYReset=yes TTYVHangup=yes [Install] Alias=display-manager.service
0
repos/ly
repos/ly/res/setup.sh
#!/bin/sh # Shell environment setup after login # Copyright (C) 2015-2016 Pier Luigi Fiorini <[email protected]> # This file is extracted from kde-workspace (kdm/kfrontend/genkdmconf.c) # Copyright (C) 2001-2005 Oswald Buddenhagen <[email protected]> # Copyright (C) 2024 The Fairy Glade # This work is free. You can redistribute it and/or modify it under the # terms of the Do What The Fuck You Want To Public License, Version 2, # as published by Sam Hocevar. See the LICENSE file for more details. # Note that the respective logout scripts are not sourced. case $SHELL in */bash) [ -z "$BASH" ] && exec $SHELL "$0" "$@" set +o posix [ -f "$CONFIG_DIRECTORY"/profile ] && . "$CONFIG_DIRECTORY"/profile if [ -f "$HOME"/.bash_profile ]; then . "$HOME"/.bash_profile elif [ -f "$HOME"/.bash_login ]; then . "$HOME"/.bash_login elif [ -f "$HOME"/.profile ]; then . "$HOME"/.profile fi ;; */zsh) [ -z "$ZSH_NAME" ] && exec $SHELL "$0" "$@" [ -d "$CONFIG_DIRECTORY"/zsh ] && zdir="$CONFIG_DIRECTORY"/zsh || zdir="$CONFIG_DIRECTORY" zhome=${ZDOTDIR:-"$HOME"} # zshenv is always sourced automatically. [ -f "$zdir"/zprofile ] && . "$zdir"/zprofile [ -f "$zhome"/.zprofile ] && . "$zhome"/.zprofile [ -f "$zdir"/zlogin ] && . "$zdir"/zlogin [ -f "$zhome"/.zlogin ] && . "$zhome"/.zlogin emulate -R sh ;; */csh|*/tcsh) # [t]cshrc is always sourced automatically. # Note that sourcing csh.login after .cshrc is non-standard. sess_tmp=$(mktemp /tmp/sess-env-XXXXXX) $SHELL -c "if (-f $CONFIG_DIRECTORY/csh.login) source $CONFIG_DIRECTORY/csh.login; if (-f ~/.login) source ~/.login; /bin/sh -c 'export -p' >! $sess_tmp" . "$sess_tmp" rm -f "$sess_tmp" ;; */fish) [ -f "$CONFIG_DIRECTORY"/profile ] && . "$CONFIG_DIRECTORY"/profile [ -f "$HOME"/.profile ] && . "$HOME"/.profile sess_tmp=$(mktemp /tmp/sess-env-XXXXXX) $SHELL --login -c "/bin/sh -c 'export -p' > $sess_tmp" . "$sess_tmp" rm -f "$sess_tmp" ;; *) # Plain sh, ksh, and anything we do not know. [ -f "$CONFIG_DIRECTORY"/profile ] && . "$CONFIG_DIRECTORY"/profile [ -f "$HOME"/.profile ] && . "$HOME"/.profile ;; esac if [ "$XDG_SESSION_TYPE" = "x11" ]; then [ -f "$CONFIG_DIRECTORY"/xprofile ] && . "$CONFIG_DIRECTORY"/xprofile [ -f "$HOME"/.xprofile ] && . "$HOME"/.xprofile # run all system xinitrc shell scripts. if [ -d "$CONFIG_DIRECTORY"/X11/xinit/xinitrc.d ]; then for i in "$CONFIG_DIRECTORY"/X11/xinit/xinitrc.d/* ; do if [ -x "$i" ]; then . "$i" fi done fi # Load Xsession scripts # OPTIONFILE, USERXSESSION, USERXSESSIONRC and ALTUSERXSESSION are required # by the scripts to work xsessionddir="$CONFIG_DIRECTORY"/X11/Xsession.d export OPTIONFILE="$CONFIG_DIRECTORY"/X11/Xsession.options export USERXSESSION="$HOME"/.xsession export USERXSESSIONRC="$HOME"/.xsessionrc export ALTUSERXSESSION="$HOME"/.Xsession if [ -d "$xsessionddir" ]; then for i in $(ls "$xsessionddir"); do script="$xsessionddir/$i" echo "Loading X session script $script" if [ -r "$script" ] && [ -f "$script" ] && expr "$i" : '^[[:alnum:]_-]\+$' > /dev/null; then . "$script" fi done fi if [ -d "$CONFIG_DIRECTORY"/X11/Xresources ]; then for i in "$CONFIG_DIRECTORY"/X11/Xresources/*; do [ -f "$i" ] && xrdb -merge "$i" done elif [ -f "$CONFIG_DIRECTORY"/X11/Xresources ]; then xrdb -merge "$CONFIG_DIRECTORY"/X11/Xresources fi [ -f "$HOME"/.Xresources ] && xrdb -merge "$HOME"/.Xresources [ -f "$XDG_CONFIG_HOME"/X11/Xresources ] && xrdb -merge "$XDG_CONFIG_HOME"/X11/Xresources if [ -f "$USERXSESSION" ]; then . "$USERXSESSION" fi fi exec "$@"
0
repos/ly/res
repos/ly/res/lang/ru.ini
capslock = capslock err_alloc = не удалось выделить память err_bounds = за пределами индекса err_chdir = не удалось открыть домашнюю папку err_console_dev = не удалось получить доступ к консоли err_dgn_oob = отладочное сообщение (log) err_domain = неверный домен err_hostname = не удалось получить имя хоста err_mlock = сбой блокировки памяти err_null = нулевой указатель err_pam = pam транзакция не удалась err_pam_abort = pam транзакция прервана err_pam_acct_expired = срок действия аккаунта истёк err_pam_auth = ошибка аутентификации err_pam_authinfo_unavail = не удалось получить информацию о пользователе err_pam_authok_reqd = токен истёк err_pam_buf = ошибка буфера памяти err_pam_cred_err = не удалось установить полномочия err_pam_cred_expired = полномочия истекли err_pam_cred_insufficient = недостаточно полномочий err_pam_cred_unavail = не удалось получить полномочия err_pam_maxtries = лимит попыток исчерпан err_pam_perm_denied = доступ запрещён err_pam_session = ошибка сессии err_pam_sys = системная ошибка err_pam_user_unknown = неизвестный пользователь err_path = не удалось установить путь err_perm_dir = не удалось изменить текущий каталог err_perm_group = не удалось понизить права доступа группы err_perm_user = не удалось понизить права доступа пользователя err_pwnam = не удалось получить информацию о пользователе err_user_gid = не удалось установить GID пользователя err_user_init = не удалось инициализировать пользователя err_user_uid = не удалось установить UID пользователя err_xsessions_dir = не удалось найти сессионную папку err_xsessions_open = не удалось открыть сессионную папку login = логин logout = logged out numlock = numlock password = пароль restart = перезагрузить shell = shell shutdown = выключить wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/cat.ini
authenticating = autenticant... brightness_down = abaixar brillantor brightness_up = apujar brillantor capslock = Bloq Majús err_alloc = assignació de memòria fallida err_bounds = índex fora de límits err_brightness_change = error en canviar la brillantor err_chdir = error en obrir la carpeta home err_console_dev = error en accedir a la consola err_dgn_oob = missatge de registre err_domain = domini invàlid err_envlist = error en obtenir l'envlist err_hostname = error en obtenir el nom de l'amfitrió err_mlock = error en bloquejar la memòria de clau err_null = punter nul err_numlock = error en establir el Bloq num err_pam = error en la transacció pam err_pam_abort = transacció pam avortada err_pam_acct_expired = compte expirat err_pam_auth = error d'autenticació err_pam_authinfo_unavail = error en obtenir la informació de l'usuari err_pam_authok_reqd = token expirat err_pam_buf = error en la memòria intermèdia err_pam_cred_err = error en establir les credencials err_pam_cred_expired = credencials expirades err_pam_cred_insufficient = credencials insuficients err_pam_cred_unavail = error en obtenir credencials err_pam_maxtries = s'ha assolit al nombre màxim d'intents err_pam_perm_denied = permís denegat err_pam_session = error de sessió err_pam_sys = error de sistema err_pam_user_unknown = usuari desconegut err_path = error en establir la ruta err_perm_dir = error en canviar el directori actual err_perm_group = error en degradar els permisos de grup err_perm_user = error en degradar els permisos de l'usuari err_pwnam = error en obtenir la informació de l'usuari err_unknown = ha ocorregut un error desconegut err_user_gid = error en establir el GID de l'usuari err_user_init = error en inicialitzar usuari err_user_uid = error en establir l'UID de l'usuari err_xauth = error en la comanda xauth err_xcb_conn = error en la connexió xcb err_xsessions_dir = error en trobar la carpeta de sessions err_xsessions_open = error en obrir la carpeta de sessions insert = inserir login = iniciar sessió logout = sessió tancada no_x11_support = x11 support disabled at compile-time no_x11_support = el suport per x11 ha estat desactivat en la compilació normal = normal numlock = Bloq Num password = Clau restart = reiniciar shell = shell shutdown = aturar sleep = suspendre wayland = wayland x11 = x11 xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/pl.ini
capslock = capslock err_alloc = nieudana alokacja pamięci err_bounds = indeks poza granicami err_chdir = nie udało się otworzyć folderu domowego err_console_dev = nie udało się uzyskać dostępu do konsoli err_dgn_oob = wiadomość loga err_domain = niepoprawna domena err_hostname = nie udało się uzyskać nazwy hosta err_mlock = nie udało się zablokować pamięci haseł err_null = wskaźnik zerowy err_pam = transakcja pam nieudana err_pam_abort = transakcja pam przerwana err_pam_acct_expired = konto wygasło err_pam_auth = błąd autentyfikacji err_pam_authinfo_unavail = nie udało się zdobyć informacji o użytkowniku err_pam_authok_reqd = token wygasł err_pam_buf = błąd bufora pamięci err_pam_cred_err = nie udało się ustawić uwierzytelnienia err_pam_cred_expired = uwierzytelnienie wygasło err_pam_cred_insufficient = niewystarczające uwierzytelnienie err_pam_cred_unavail = nie udało się uzyskać uwierzytelnienia err_pam_maxtries = osiągnięto limit prób err_pam_perm_denied = brak uprawnień err_pam_session = błąd sesji err_pam_sys = błąd systemu err_pam_user_unknown = nieznany użytkownik err_path = nie udało się ustawić ścieżki err_perm_dir = nie udało się zmienić obecnego katalogu err_perm_group = nie udało się obniżyć uprawnień grupy err_perm_user = nie udało się obniżyć uprawnień użytkownika err_pwnam = nie udało się uzyskać informacji o użytkowniku err_user_gid = nie udało się ustawić GID użytkownika err_user_init = nie udało się zainicjalizować użytkownika err_user_uid = nie udało się ustawić UID użytkownika err_xsessions_dir = nie udało się znaleźć folderu sesji err_xsessions_open = nie udało się otworzyć folderu sesji login = login logout = wylogowano numlock = numlock password = hasło restart = uruchom ponownie shell = powłoka shutdown = wyłącz wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/es.ini
authenticating = autenticando... brightness_down = bajar brillo brightness_up = subir brillo capslock = Bloq Mayús err_alloc = asignación de memoria fallida err_bounds = índice fuera de límites err_chdir = error al abrir la carpeta home err_console_dev = error al acceder a la consola err_dgn_oob = mensaje de registro err_domain = dominio inválido err_hostname = error al obtener el nombre de host err_mlock = error al bloquear la contraseña de memoria err_null = puntero nulo err_pam = error en la transacción pam err_pam_abort = transacción pam abortada err_pam_acct_expired = cuenta expirada err_pam_auth = error de autenticación err_pam_authinfo_unavail = error al obtener información del usuario err_pam_authok_reqd = token expirado err_pam_buf = error de la memoria intermedia err_pam_cred_err = error al establecer las credenciales err_pam_cred_expired = credenciales expiradas err_pam_cred_insufficient = credenciales insuficientes err_pam_cred_unavail = error al obtener credenciales err_pam_maxtries = se ha alcanzado el límite de intentos err_pam_perm_denied = permiso denegado err_pam_session = error de sesión err_pam_sys = error de sistema err_pam_user_unknown = usuario desconocido err_path = error al establecer la ruta err_perm_dir = error al cambiar el directorio actual err_perm_group = error al degradar los permisos del grupo err_perm_user = error al degradar los permisos del usuario err_pwnam = error al obtener la información del usuario err_user_gid = error al establecer el GID del usuario err_user_init = error al inicializar usuario err_user_uid = error al establecer el UID del usuario err_xsessions_dir = error al buscar la carpeta de sesiones err_xsessions_open = error al abrir la carpeta de sesiones insert = insertar login = usuario logout = cerrar sesión no_x11_support = soporte para x11 deshabilitado en tiempo de compilación normal = normal numlock = Bloq Num other = otro password = contraseña restart = reiniciar shell = shell shutdown = apagar sleep = suspender wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/sv.ini
capslock = capslock err_alloc = misslyckad minnesallokering err_bounds = utanför banan index err_chdir = misslyckades att öppna hemkatalog err_console_dev = misslyckades att komma åt konsol err_dgn_oob = loggmeddelande err_domain = okänd domän err_hostname = misslyckades att hämta värdnamn err_mlock = misslyckades att låsa lösenordsminne err_null = nullpekare err_pam = pam-transaktion misslyckades err_pam_abort = pam-transaktion avbröts err_pam_acct_expired = konto upphört err_pam_auth = autentiseringsfel err_pam_authinfo_unavail = misslyckades att hämta användarinfo err_pam_authok_reqd = token utgången err_pam_buf = minnesbuffer fel err_pam_cred_err = misslyckades att ställa in inloggningsuppgifter err_pam_cred_expired = inloggningsuppgifter upphörda err_pam_cred_insufficient = otillräckliga inloggningsuppgifter err_pam_cred_unavail = misslyckades att hämta inloggningsuppgifter err_pam_maxtries = nådde maximal försöksgräns err_pam_perm_denied = åtkomst nekad err_pam_session = sessionsfel err_pam_sys = systemfel err_pam_user_unknown = okänd användare err_path = misslyckades att ställa in sökväg err_perm_dir = misslyckades att ändra aktuell katalog err_perm_group = misslyckades att nergradera gruppbehörigheter err_perm_user = misslyckades att nergradera användarbehörigheter err_pwnam = misslyckades att hämta användarinfo err_user_gid = misslyckades att ställa in användar-GID err_user_init = misslyckades att initialisera användaren err_user_uid = misslyckades att ställa in användar-UID err_xsessions_dir = misslyckades att hitta sessionskatalog err_xsessions_open = misslyckades att öppna sessionskatalog login = inloggning logout = utloggad numlock = numlock password = lösenord restart = starta om shell = skal shutdown = stäng av wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/it.ini
capslock = capslock err_alloc = impossibile allocare memoria err_bounds = indice fuori limite err_chdir = impossibile aprire home directory err_console_dev = impossibile aprire console err_dgn_oob = messaggio log err_domain = dominio non valido err_hostname = impossibile ottenere hostname err_mlock = impossibile ottenere lock per la password in memoria err_null = puntatore nullo err_pam = transazione PAM fallita err_pam_abort = transazione PAM interrotta err_pam_acct_expired = account scaduto err_pam_auth = errore di autenticazione err_pam_authinfo_unavail = impossibile ottenere informazioni utente err_pam_authok_reqd = token scaduto err_pam_buf = errore buffer memoria err_pam_cred_err = impossibile impostare credenziali err_pam_cred_expired = credenziali scadute err_pam_cred_insufficient = credenziali insufficienti err_pam_cred_unavail = impossibile ottenere credenziali err_pam_maxtries = raggiunto limite tentativi err_pam_perm_denied = permesso negato err_pam_session = errore di sessione err_pam_sys = errore di sistema err_pam_user_unknown = utente sconosciuto err_path = impossibile impostare percorso err_perm_dir = impossibile cambiare directory corrente err_perm_group = impossibile ridurre permessi gruppo err_perm_user = impossibile ridurre permessi utente err_pwnam = impossibile ottenere dati utente err_user_gid = impossibile impostare GID utente err_user_init = impossibile inizializzare utente err_user_uid = impossible impostare UID utente err_xsessions_dir = impossibile localizzare cartella sessioni err_xsessions_open = impossibile aprire cartella sessioni login = username logout = scollegato numlock = numlock password = password restart = riavvio shell = shell shutdown = arresto wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/en.ini
authenticating = authenticating... brightness_down = decrease brightness brightness_up = increase brightness capslock = capslock err_alloc = failed memory allocation err_bounds = out-of-bounds index err_brightness_change = failed to change brightness err_chdir = failed to open home folder err_console_dev = failed to access console err_dgn_oob = log message err_domain = invalid domain err_envlist = failed to get envlist err_hostname = failed to get hostname err_mlock = failed to lock password memory err_null = null pointer err_numlock = failed to set numlock err_pam = pam transaction failed err_pam_abort = pam transaction aborted err_pam_acct_expired = account expired err_pam_auth = authentication error err_pam_authinfo_unavail = failed to get user info err_pam_authok_reqd = token expired err_pam_buf = memory buffer error err_pam_cred_err = failed to set credentials err_pam_cred_expired = credentials expired err_pam_cred_insufficient = insufficient credentials err_pam_cred_unavail = failed to get credentials err_pam_maxtries = reached maximum tries limit err_pam_perm_denied = permission denied err_pam_session = session error err_pam_sys = system error err_pam_user_unknown = unknown user err_path = failed to set path err_perm_dir = failed to change current directory err_perm_group = failed to downgrade group permissions err_perm_user = failed to downgrade user permissions err_pwnam = failed to get user info err_unknown = an unknown error occurred err_user_gid = failed to set user GID err_user_init = failed to initialize user err_user_uid = failed to set user UID err_xauth = xauth command failed err_xcb_conn = xcb connection failed err_xsessions_dir = failed to find sessions folder err_xsessions_open = failed to open sessions folder insert = insert login = login logout = logged out normal = normal no_x11_support = x11 support disabled at compile-time numlock = numlock password = password restart = reboot shell = shell shutdown = shutdown sleep = sleep wayland = wayland xinitrc = xinitrc x11 = x11
0
repos/ly/res
repos/ly/res/lang/sr.ini
capslock = capslock err_alloc = neuspijesna alokacija memorije err_bounds = izvan granica indeksa err_chdir = neuspijesno otvaranje home foldera err_console_dev = neuspijesno pristupanje konzoli err_dgn_oob = log poruka err_domain = nevazeci domen err_hostname = neuspijesno trazenje hostname-a err_mlock = neuspijesno zakljucavanje memorije lozinke err_null = null pokazivac err_pam = pam transakcija neuspijesna err_pam_abort = pam transakcija prekinuta err_pam_acct_expired = nalog istekao err_pam_auth = greska pri autentikaciji err_pam_authinfo_unavail = neuspjelo uzimanje informacija o korisniku err_pam_authok_reqd = token istekao err_pam_buf = greska bafera memorije err_pam_cred_err = neuspjelo postavljanje kredencijala err_pam_cred_expired = kredencijali istekli err_pam_cred_insufficient = nedovoljni kredencijali err_pam_cred_unavail = neuspjelo uzimanje kredencijala err_pam_maxtries = dostignut maksimalan broj pokusaja err_pam_perm_denied = nedozovoljeno err_pam_session = greska sesije err_pam_sys = greska sistema err_pam_user_unknown = nepoznat korisnik err_path = neuspjelo postavljanje path-a err_perm_dir = neuspjelo mijenjanje foldera err_perm_group = neuspjesno snizavanje dozvola grupe err_perm_user = neuspijesno snizavanje dozvola korisnika err_pwnam = neuspijesno skupljanje informacija o korisniku err_user_gid = neuspijesno postavljanje korisničkog GID-a err_user_init = neuspijensa inicijalizacija korisnika err_user_uid = neuspijesno postavljanje UID-a korisnika err_xsessions_dir = neuspijesno pronalazenje foldera sesija err_xsessions_open = neuspijesno otvaranje foldera sesija login = korisnik logout = izlogovan numlock = numlock password = lozinka restart = ponovo pokreni shell = shell shutdown = ugasi wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/fr.ini
authenticating = authentification... brightness_down = diminuer la luminosité brightness_up = augmenter la luminosité capslock = verr.maj err_alloc = échec d'allocation mémoire err_bounds = indice hors-limite err_brightness_change = échec du changement de luminosité err_chdir = échec de l'ouverture du répertoire home err_console_dev = échec d'accès à la console err_dgn_oob = message err_domain = domaine invalide err_envlist = échec de lecture de la liste d'environnement err_hostname = échec de lecture du nom d'hôte err_mlock = échec du verrouillage mémoire err_null = pointeur null err_numlock = échec de modification du verr.num err_pam = échec de la transaction pam err_pam_abort = transaction pam avortée err_pam_acct_expired = compte expiré err_pam_auth = erreur d'authentification err_pam_authinfo_unavail = échec de l'obtention des infos utilisateur err_pam_authok_reqd = tiquet expiré err_pam_buf = erreur de mémoire tampon err_pam_cred_err = échec de la modification des identifiants err_pam_cred_expired = identifiants expirés err_pam_cred_insufficient = identifiants insuffisants err_pam_cred_unavail = échec de l'obtention des identifiants err_pam_maxtries = limite d'essais atteinte err_pam_perm_denied = permission refusée err_pam_session = erreur de session err_pam_sys = erreur système err_pam_user_unknown = utilisateur inconnu err_path = échec de la modification du path err_perm_dir = échec de changement de répertoire err_perm_group = échec du déclassement des permissions de groupe err_perm_user = échec du déclassement des permissions utilisateur err_pwnam = échec de lecture des infos utilisateur err_unknown = une erreur inconnue est survenue err_user_gid = échec de modification du GID err_user_init = échec d'initialisation de l'utilisateur err_user_uid = échec de modification du UID err_xauth = échec de la commande xauth err_xcb_conn = échec de la connexion xcb err_xsessions_dir = échec de la recherche du dossier de sessions err_xsessions_open = échec de l'ouverture du dossier de sessions insert = insertion login = identifiant logout = déconnecté normal = normal no_x11_support = support pour x11 désactivé lors de la compilation numlock = verr.num password = mot de passe restart = redémarrer shell = shell shutdown = éteindre sleep = veille wayland = wayland xinitrc = xinitrc x11 = x11
0
repos/ly/res
repos/ly/res/lang/uk.ini
capslock = capslock err_alloc = невдале виділення пам'яті err_bounds = поза межами індексу err_chdir = не вдалося відкрити домашній каталог err_console_dev = невдалий доступ до консолі err_dgn_oob = повідомлення журналу (log) err_domain = недійсний домен err_hostname = не вдалося отримати ім'я хосту err_mlock = збій блокування пам'яті err_null = нульовий вказівник err_pam = невдала pam транзакція err_pam_abort = pam транзакція перервана err_pam_acct_expired = термін дії акаунту вичерпано err_pam_auth = помилка автентифікації err_pam_authinfo_unavail = не вдалося отримати дані користувача err_pam_authok_reqd = термін дії токена вичерпано err_pam_buf = помилка буферу пам'яті err_pam_cred_err = не вдалося змінити облікові дані err_pam_cred_expired = термін дії повноважень вичерпано err_pam_cred_insufficient = недостатньо облікових даних err_pam_cred_unavail = не вдалося отримати облікові дані err_pam_maxtries = вичерпано ліміт спроб err_pam_perm_denied = відмовлено у доступі err_pam_session = помилка сесії err_pam_sys = системна помилка err_pam_user_unknown = невідомий користувач err_path = не вдалося змінити шлях err_perm_dir = не вдалося змінити поточний каталог err_perm_group = не вдалося понизити права доступу групи err_perm_user = не вдалося понизити права доступу користувача err_pwnam = не вдалося отримати дані користувача err_user_gid = не вдалося змінити GID користувача err_user_init = не вдалося ініціалізувати користувача err_user_uid = не вдалося змінити UID користувача err_xsessions_dir = не вдалося знайти каталог сесій err_xsessions_open = не вдалося відкрити каталог сесій login = логін logout = вийти numlock = numlock password = пароль restart = перезавантажити shell = оболонка shutdown = вимкнути wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/cs.ini
capslock = capslock err_alloc = alokace paměti selhala err_bounds = index je mimo hranice pole err_chdir = nelze otevřít domovský adresář err_console_dev = chyba při přístupu do konzole err_dgn_oob = zpráva protokolu err_domain = neplatná doména err_hostname = nelze získat název hostitele err_mlock = uzamčení paměti hesel selhalo err_null = nulový ukazatel err_pam = pam transakce selhala err_pam_abort = pam transakce přerušena err_pam_acct_expired = platnost účtu vypršela err_pam_auth = chyba autentizace err_pam_authinfo_unavail = nelze získat informace o uživateli err_pam_authok_reqd = platnost tokenu vypršela err_pam_buf = chyba vyrovnávací paměti err_pam_cred_err = nelze nastavit pověření err_pam_cred_expired = platnost pověření vypršela err_pam_cred_insufficient = nedostatečné pověření err_pam_cred_unavail = nepodařilo se získat pověření err_pam_maxtries = byl dosažen maximální počet pokusů err_pam_perm_denied = přístup odepřen err_pam_session = chyba relace err_pam_sys = systemová chyba err_pam_user_unknown = neznámý uživatel err_path = nepodařilo se nastavit cestu err_perm_dir = nepodařilo se změnit adresář err_perm_group = nepodařilo se snížit skupinová oprávnění err_perm_user = nepodařilo se snížit uživatelská oprávnění err_pwnam = nelze získat informace o uživateli err_user_gid = nastavení GID uživatele selhalo err_user_init = inicializace uživatele selhala err_user_uid = nastavení UID uživateli selhalo err_xsessions_dir = nepodařilo se najít složku relací err_xsessions_open = nepodařilo se otevřít složku relací login = uživatel logout = odhlášen numlock = numlock password = heslo restart = restartovat shell = příkazový řádek shutdown = vypnout wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/de.ini
capslock = Feststelltaste err_alloc = Speicherzuweisung fehlgeschlagen err_bounds = Listenindex ist außerhalb des Bereichs err_chdir = Fehler beim oeffnen des home-ordners err_console_dev = Zugriff auf die Konsole fehlgeschlagen err_dgn_oob = Protokoll Nachricht err_domain = Unzulaessige domain err_hostname = Holen des Hostnames fehlgeschlagen err_mlock = Abschließen des Passwortspeichers fehlgeschlagen err_null = Null Zeiger err_pam = pam Transaktion fehlgeschlagen err_pam_abort = pam Transaktion abgebrochen err_pam_acct_expired = Benutzerkonto abgelaufen err_pam_auth = Authentifizierungs Fehler err_pam_authinfo_unavail = holen der Benutzerinformationen fehlgeschlagen err_pam_authok_reqd = Schluessel abgelaufen err_pam_buf = Speicherpufferfehler err_pam_cred_err = Fehler beim setzen der Anmeldedaten err_pam_cred_expired = Anmeldedaten abgelaufen err_pam_cred_insufficient = Anmeldedaten unzureichend err_pam_cred_unavail = Fehler beim holen der Anmeldedaten err_pam_maxtries = Maximale Versuche erreicht err_pam_perm_denied = Zugriff Verweigert err_pam_session = Sitzungsfehler err_pam_sys = Systemfehler err_pam_user_unknown = Unbekannter Nutzer err_path = Fehler beim setzen des Pfades err_perm_dir = Fehler beim wechseln des Ordners err_perm_group = Fehler beim heruntersetzen der Gruppen Berechtigungen err_perm_user = Fehler beim heruntersetzen der Nutzer Berechtigungen err_pwnam = Holen der Benutzerinformationen fehlgeschlagen err_user_gid = Fehler beim setzen der Gruppen Id des Nutzers err_user_init = Initialisierung des Nutzers fehlgeschlagen err_user_uid = Setzen der Benutzer Id fehlgeschlagen err_xsessions_dir = Fehler beim finden des Sitzungsordners err_xsessions_open = Fehler beim öffnen des Sitzungsordners login = Anmelden logout = Abgemeldet numlock = Numtaste password = Passwort restart = Neustarten shell = shell shutdown = Herunterfahren wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/pt.ini
capslock = capslock err_alloc = erro na atribuição de memória err_bounds = índice fora de limites err_chdir = erro ao abrir a pasta home err_console_dev = erro ao aceder à consola err_dgn_oob = mensagem de registo err_domain = domínio inválido err_hostname = erro ao obter o nome do host err_mlock = erro de bloqueio de memória err_null = ponteiro nulo err_pam = erro na transação pam err_pam_abort = transação pam abortada err_pam_acct_expired = conta expirada err_pam_auth = erro de autenticação err_pam_authinfo_unavail = erro ao obter informação do utilizador err_pam_authok_reqd = token expirado err_pam_buf = erro de buffer de memória err_pam_cred_err = erro ao definir credenciais err_pam_cred_expired = credenciais expiradas err_pam_cred_insufficient = credenciais insuficientes err_pam_cred_unavail = erro ao obter credenciais err_pam_maxtries = limite máximo de tentativas atingido err_pam_perm_denied = permissão negada err_pam_session = erro de sessão err_pam_sys = erro de sistema err_pam_user_unknown = utilizador desconhecido err_path = erro ao definir o caminho de acesso err_perm_dir = erro ao alterar o diretório atual err_perm_group = erro ao reduzir as permissões do grupo err_perm_user = erro ao reduzir as permissões do utilizador err_pwnam = erro ao obter informação do utilizador err_user_gid = erro ao definir o GID do utilizador err_user_init = erro ao iniciar o utilizador err_user_uid = erro ao definir o UID do utilizador err_xsessions_dir = erro ao localizar a pasta das sessões err_xsessions_open = erro ao abrir a pasta das sessões login = iniciar sessão logout = terminar sessão numlock = numlock password = palavra-passe restart = reiniciar shell = shell shutdown = encerrar wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/pt_BR.ini
capslock = caixa alta err_alloc = alocação de memória malsucedida err_bounds = índice fora de limites err_chdir = não foi possível abrir o diretório home err_console_dev = não foi possível acessar o console err_dgn_oob = mensagem de log err_domain = domínio inválido err_hostname = não foi possível obter o nome do host err_mlock = bloqueio da memória de senha malsucedido err_null = ponteiro nulo err_pam = transação pam malsucedida err_pam_abort = transação pam abortada err_pam_acct_expired = conta expirada err_pam_auth = erro de autenticação err_pam_authinfo_unavail = não foi possível obter informações do usuário err_pam_authok_reqd = token expirada err_pam_buf = erro de buffer de memória err_pam_cred_err = erro para definir credenciais err_pam_cred_expired = credenciais expiradas err_pam_cred_insufficient = credenciais insuficientes err_pam_cred_unavail = não foi possível obter credenciais err_pam_maxtries = limite máximo de tentativas atingido err_pam_perm_denied = permissão negada err_pam_session = erro de sessão err_pam_sys = erro de sistema err_pam_user_unknown = usuário desconhecido err_path = não foi possível definir o caminho err_perm_dir = não foi possível alterar o diretório atual err_perm_group = não foi possível reduzir as permissões de grupo err_perm_user = não foi possível reduzir as permissões de usuário err_pwnam = não foi possível obter informações do usuário err_user_gid = não foi possível definir o GID do usuário err_user_init = não foi possível iniciar o usuário err_user_uid = não foi possível definir o UID do usuário err_xsessions_dir = não foi possível encontrar a pasta das sessões err_xsessions_open = não foi possível abrir a pasta das sessões login = conectar logout = desconectado numlock = numlock password = senha restart = reiniciar shell = shell shutdown = desligar wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/tr.ini
capslock = capslock err_alloc = basarisiz bellek ayirma err_bounds = sinirlarin disinda dizin err_chdir = ev klasoru acilamadi err_console_dev = konsola erisilemedi err_dgn_oob = log mesaji err_domain = gecersiz etki alani err_hostname = ana bilgisayar adi alinamadi err_mlock = parola bellegi kilitlenemedi err_null = bos isaretci hatasi err_pam = pam islemi basarisiz oldu err_pam_abort = pam islemi durduruldu err_pam_acct_expired = hesabin suresi dolmus err_pam_auth = kimlik dogrulama hatasi err_pam_authinfo_unavail = kullanici bilgileri getirilirken hata olustu err_pam_authok_reqd = suresi dolmus token err_pam_buf = bellek arabellegi hatasi err_pam_cred_err = kimlik bilgileri ayarlanamadi err_pam_cred_expired = kimlik bilgilerinin suresi dolmus err_pam_cred_insufficient = yetersiz kimlik bilgileri err_pam_cred_unavail = kimlik bilgileri alinamadi err_pam_maxtries = en fazla deneme sinirina ulasildi err_pam_perm_denied = izin reddedildi err_pam_session = oturum hatasi err_pam_sys = sistem hatasi err_pam_user_unknown = bilinmeyen kullanici err_path = yol ayarlanamadi err_perm_dir = gecerli dizin degistirilemedi err_perm_group = grup izinleri dusurulemedi err_perm_user = kullanici izinleri dusurulemedi err_pwnam = kullanici bilgileri alinamadi err_user_gid = kullanici icin GID ayarlanamadi err_user_init = kullanici oturumu baslatilamadi err_user_uid = kullanici icin UID ayarlanamadi err_xsessions_dir = oturumlar klasoru bulunamadi err_xsessions_open = oturumlar klasoru acilamadi login = kullanici logout = oturumdan cikis yapildi numlock = numlock password = sifre restart = yeniden baslat shell = shell shutdown = makineyi kapat wayland = wayland xinitrc = xinitrc
0
repos/ly/res
repos/ly/res/lang/ro.ini
capslock = capslock err_console_dev = nu s-a putut accesa consola err_pam_abort = tranzacţie pam anulată err_pam_acct_expired = cont expirat err_pam_auth = eroare de autentificare err_pam_authinfo_unavail = nu s-au putut obţine informaţii despre utilizator err_pam_authok_reqd = token expirat err_pam_buf = eroare de memorie (buffer) err_pam_cred_err = nu s-au putut seta date de identificare (credentials) err_pam_cred_expired = datele de identificare (credentials) au expirat err_pam_cred_insufficient = date de identificare (credentials) insuficiente err_pam_cred_unavail = nu s-au putut obţine date de indentificare (credentials) err_pam_maxtries = s-a atins numărul maxim de încercări err_pam_perm_denied = acces interzis err_pam_session = eroare de sesiune err_pam_sys = eroare de sistem err_pam_user_unknown = utilizator necunoscut err_perm_dir = nu s-a putut schimba dosarul (folder-ul) curent err_perm_group = nu s-a putut face downgrade permisiunilor de grup err_perm_user = nu s-a putut face downgrade permisiunilor de utilizator login = utilizator logout = opreşte sesiunea numlock = numlock password = parolă restart = resetează shell = shell shutdown = opreşte sistemul wayland = wayland xinitrc = xinitrc
0
repos
repos/zig-cuckoofilter/example.zig
const std = @import("std"); const hasher = std.hash.Fnv1a_64; const cuckoo = @import("./src/cuckoofilter.zig"); fn fingerprint8(x: []const u8) u8 { return x[0]; } fn fingerprint32(x: []const u8) u32 { // Just a sample strategy, not suitable for all types // of input. Imagine if you were adding images to the // filter: all fingerprints would be the same because // most formats have a standard header. In that case // you want to make sure to use the actual graphical // data to pluck your fingerprint from. return @bytesToSlice(u32, x[0..@sizeOf(u32)])[0]; } pub fn main() !void { // Assume we want to keep track of max 1 Million items. const universe_size = 1000000; // Let's use Filter8, a filter with 1 byte long // fingerprints and a 3% max *false positive* error rate. // Note: Cuckoo filters cannot produce false negatives. // Error % information: _ = cuckoo.Filter8.MaxError; // ╚═> 3.125e-02 (~0.03, i.e. 3%) _ = cuckoo.Filter16.MaxError; // ╚═> 1.22070312e-04 (~0.0001, i.e. 0.01%) _ = cuckoo.Filter32.MaxError; // ╚═> 9.31322574e-10 (~0.000000001, i.e. 0.0000001%) // First let's calculate how big the filter has to be: const memsize = comptime cuckoo.Filter8.size_for(universe_size); // The value of memsize has to be a power of two and it // is *strongly* recommended to keep the fill rate of a // filter under 80%. size_for() will pad the number for // you automatically and then round up to the closest // power of 2. size_for_exactly() will not apply any // padding before rounding up. // Use capacity() to know how many items a slice of memory // can store for the given filter type. _ = cuckoo.Filter8.capacity(memsize); // => 2097152 // Note: this function will return the theoretical maximum // capacity, without subtracting any padding. It's smart // to adjust your expectations to match how much memory // you have to allocate anyway, but don't get too greedy. // I say `theoretical` because an overfilled filter will // start refusing inserts with a TooFull error. // This is how you allocate static memory for the filter: var memory: [memsize]u8 align(cuckoo.Filter8.Align) = undefined; // Note: the filter benefits from a specific alignment // (which differs from type to type) so you must specify it // when allocating memory. Failing to do so will result in // a comptime error. // Instantiating a filter var cf8 = try cuckoo.Filter8.init(memory[0..]); // // FILTER USAGE // const banana_h = hasher.hash("banana"); const banana_fp = fingerprint8("banana"); const apple_h = hasher.hash("apple"); const apple_fp = fingerprint8("apple"); _ = try cf8.maybe_contains(banana_h, banana_fp); // => false _ = try cf8.count(); // => 0 try cf8.add(banana_h, banana_fp); _ = try cf8.maybe_contains(banana_h, banana_fp); // => true _ = try cf8.maybe_contains(apple_h, apple_fp); // => false _ = try cf8.count(); // => 1 try cf8.remove(banana_h, banana_fp); _ = try cf8.maybe_contains(banana_h, banana_fp); // => false _ = try cf8.count(); // => 0 // The filter can also be used with dynamic memory. // It's up to you to manage that via an allocator. const example_allocator = std.heap.c_allocator; // Don't forget to free the memory afterwards. const memsize32 = comptime cuckoo.Filter32.size_for_exactly(64); var dyn_memory = try example_allocator.alignedAlloc(u8, cuckoo.Filter32.Align, memsize32); defer example_allocator.free(dyn_memory); var dyn_cf32 = try example_allocator.create(cuckoo.Filter32); defer example_allocator.destroy(dyn_cf32); dyn_cf32.* = try cuckoo.Filter32.init(dyn_memory); // When restoring a persisted filter, you should only persist the individual fields // as, for example, .buckets is a slice that points to `dyn_memory` which would be // invalid upon restore (wrong pointer) and just a waste of space when stored. // Upon loading, to reconnect the filter and its `dyn_memory`, use bytesToBuckets. // Here's an example (which is not necessary to make this script work, as we just created // the entire filter): // // dyn_cf32.buckets = cuckoo.Filter32.bytesToBuckets(dyn_memory); // // USAGE FAILURE SCENARIOS // // 1. Adding too many colliding items (because of bad entropy or // because you are adding multiple copies of the same item) const pear_h = hasher.hash("pear"); const pear_fp = fingerprint32("pear"); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); // No more space for items with equal hash and fp, // next insert will fail. dyn_cf32.add(pear_h, pear_fp) catch |err| switch (err) { error.TooFull => std.debug.warn("yep, too full\n"), else => unreachable, }; // Other inserts that don't collide can still succeed const orange_h = hasher.hash("orange"); const orange_fp = fingerprint32("orange"); try dyn_cf32.add(orange_h, orange_fp); // 2. You can only delete elements that were inserted before. // Trying to delete a non-existing item has a chance of // breaking the filter (makes false negatives possible). // Deleting a non-existing item can either cause the // deletion of another colliding item or fail to find // a matching fingerprint in the filter. In the second // case the filter locks down and returns an error for // all operations, as it is now impossible to know what // the correct state would be. dyn_cf32.remove(0, 0) catch |err| switch (err) { error.Broken => std.debug.warn(".remove, broken\n"), }; _ = dyn_cf32.is_broken(); // => true dyn_cf32.add(orange_fp, orange_fp) catch |err| switch (err) { error.Broken => std.debug.warn(".add, broken\n"), error.TooFull => {}, }; if (dyn_cf32.count()) |_| { std.debug.warn(".count, works\n"); // won't be printed } else |err| switch (err) { error.Broken => std.debug.warn(".count, broken\n") } // Since searching does not mutate the filter, if the item // is found, no error is returned: _ = try dyn_cf32.maybe_contains(orange_h, orange_fp); // => true // But if an item is not found, we don't know if it was wrongly // deleted or not, so the filter has to return an error in order // to ensure that it does not return a false negative response. if (dyn_cf32.maybe_contains(0, 0)) |_| { std.debug.warn(".maybe_contains, works\n"); // won't be printed } else |err| switch (err) { error.Broken => std.debug.warn(".maybe_contains, broken\n") } // You should *NEVER* get into that situation. If you do, it's // a programming error. If your program runs in an environment // where a request that involves the filter might be repeated // (e.g. web servers), mark each request by a unique ID and // keep some kind of commit log to ensure you don't run the // same request twice, as it's semantically wrong to expect // idempotence from Cuckoo filter commands. // 3. Other small errors could be trying to pass to init memory // with the wrong alignment or a wrong buffer size. Try to // use the provided functions (i.e. size_for, size_for_exactly) // to always have your buffers be the right size. You can // also use those functions to reason about your data and even // opt not to use a filter if the tradeoff is not worth it. if (cuckoo.Filter8.init(memory[1..13])) |_| { std.debug.warn(".init, works\n"); // won't be printed } else |err| switch (err) { error.BadLength => std.debug.warn(".init failed, use .size_for()!\n") } // // FIXING TOO FULL // // Filter8 and Filter16 have 4 element-wide buckets, // while Filter32 has 2 element-wide buckets. // Each fingerprint has two buckets that can be used to // house it. This means that you can have, respectively, // up to 8 (F8, F16) and 4 (F32) collisions/copies before both // buckets fill completely and you get TooFull. In practice, // you get an extra chance because of how filters work internally. // There's a special slot that houses a single fingerprint that // could not find space in one of its 2 candidate slots. // The problem is that once that "safety" slot is filled, the // filter becomes much more succeptible to collisions and is forced // to return TooFull when in fact it could try to make space. // If you are also deleting elements from the filter, and // not just adding them, this is what you can do to try and // recover from that situation. // Returns true if the safety slot is occupied. var bad_situation = dyn_cf32.is_toofull(); // Note that you might not have ever received a TooFull error for // this function to return true. In our previous example with // dyn_cf32, it took us 5 insertions to obtain a TooFull error. // This function would return true after 4. // Try to fix the situation: if (bad_situation) { dyn_cf32.fix_toofull() catch |err| switch (err) { error.Broken => {}, error.TooFull => {}, }; } // With this function you can only fix TooFull, not Broken. // If fix_toofull returns TooFull, it means that it failed. // In practice you will need to free more elements before // being able to fix the situation, but in theory calling // the function multiple times might eventually fix the // situation (i.e. it can make progress each call). // That said, going back to practical usage, you are probably // in a problematic situation when it gets to that point. // To ensure you never have to deal with these problems, // make sure you: // (1) Never overfill/undersize a filter. // (2) Get entropy right for the fingerprinting function. // // A trick to get (2) right is to pluck it not out of the // original element, but out of hash2(element). Just make sure // you use a different hasing function, independent from the // fitst one, otherwise you're going to still end up with too // little entropy, and be aware of the increased computational // cost. Secondary hashing might be worth it for semi-strucutred // data where you might find it hard to know if you're plucking // "variable" data or part of the structure (e.g. JSON data), // since the latter is bound to have lower entropy. // // PRNG Stuff // // Cuckoo Filters need a random number generator to decide which // fingerprint to evict when a given bucket pair is full. This // library provides a default implementation that uses the Zig // standard library's Xoroshiro implementation, seeded by default to 42. // If your application has short-lived sessions, a static seed won't be // good enough, as it will basically result in giving out the same // number over and over again, similarly to what is shown in that one // dilbert strip. To fix that use seed_default_prng: var buf: [8]u8 = undefined; try std.crypto.randomBytes(buf[0..]); const seed = std.mem.readIntSliceLittle(u64, buf[0..8]); cuckoo.seed_default_prng(seed); // Additionally, you might also want to provide your own PRNG // implementation, either because you have specific needs (CSPRNG) or // because you might want to make the filter fully deterministic and thus // need to be able to persist and restore the PRNG's state. // You can customize the PRNG of each filter by providing an appropriate // function pointer: dyn_cf32.rand_fn = DilbertRandom; // From now on `dyn_cf32` will stop using the default implementation // (shared by default by all filters) and will instead only use the // provided function. If you use this functionality, *make sure to // set the function pointer again when loading the filter from disk*. // If you're fine with the default implementation and want more control // than just seeding, use .get_default_prng_state() and // .set_default_prng_state(), but beware that you are modifying a // "singleton" struct used by all filters. If you are in a multi-threaded // context this might cause problems if you are executing // .add / .delete / .fix_toofull and altering the prng singleton at the // same time. In that case you will have to customize .rand_fn } fn DilbertRandom() u1 { return 1; }
0
repos
repos/zig-cuckoofilter/README.md
<h1 align="center">zig-cuckoofilter</h1> <p align="center"> <a href="https://github.com/kristoff-it/zig-cuckoofilter/releases/latest"><img src="https://badgen.net/github/release/kristoff-it/zig-cuckoofilter"/></a> <a href="LICENSE.md"><img src="https://badgen.net/github/license/kristoff-it/zig-cuckoofilter" /></a> <a href="https://twitter.com/croloris"><img src="https://badgen.net/badge/twitter/@croloris/1DA1F2?icon&label" /></a> </p> <p align="center"> Production-ready Cuckoo Filters for any C ABI compatible target. </p> Used by ------- [![kristoff-it/redis-cuckoofilter - GitHub](https://gh-card.dev/repos/kristoff-it/redis-cuckoofilter.svg)](https://github.com/kristoff-it/redis-cuckoofilter) What's a Cuckoo Filter? ----------------------- Cuckoo filters are a probabilistic data structure that allows you to test for membership of an element in a set without having to hold the whole set in memory. This is done at the cost of having a probability of getting a false positive response, which, in other words, means that they can only answer "Definitely no" or "Probably yes". The false positive probability is roughly inversely related to how much memory you are willing to allocate to the filter. The most iconic data structure used for this kind of task are Bloom filters but Cuckoo filters boast both better practical performance and efficiency, and, more importantly, the ability of **deleting elements from the filter**. Bloom filters only support insertion of new items. Some extensions of Bloom filters have the ability of deleting items but they achieve so at the expense of precision or memory usage, resulting in a far worse tradeoff compared to what Cuckoo filters offer. What Makes This Library Interesting ----------------------------------- ### It's production-ready Most Cuckoo Filter implementations available on GitHub get the computer science aspect right but fail at the engineering level, rendering each basically unsuitable for most serious use cases. These problems go from not offering a way to persit and restore the filter, up to silent corruption of the filter when its fill-rate increases too much (because the implementation has no vacant/homeless slot). This implementation covers all these aspects in full, giving to you complete control over the filter while making sure that misusage gets **always** properly reported. ### It's for advanced users Instead of making a Bloom-like interface, I leave to the caller to choose a hashing function to use, and which byte(s) of the original item to use as fingerprint. This would not produce good ergonomics with Bloom filters as they rely on multiple hashings (dozens for low error rates!). This requires the user to know the basics of hashing and how these data structures work but on the upside: - If you are already handling hashed values, no superfluous work is done. - To perform well, Cuckoo filters rely on a good choice of fingerprint for each item, and it should not be left to the library. - **The hash function can be decided by you, meaning that this library is hashing-function agnostic**. ### It's written in Zig (https://ziglang.org) Which means that the code is clear, free of C gotchas, and that you can dynamically link to it from any C ABI compatible language. Zig is simpler and safer than C but operates at the same abstraction level (i.e. no gc, explicit memory management, pointers, etc). Zig can compile C code and Zig shared object files can be used in a normal C compilation process. ### It doesn't manage memory All memory allocation/freeing is done by the caller. This makes this library suitable for embedding in any kind of ecosystem. For example, take a look at [kristoff-it/redis-cuckoofilter](https://github.com/kristoff-it/redis-cuckoofilter). Using zig-cuckoofilter from C or other languages (Python, Go, JavaScript, ...) ------------------------------------------------------------------------------ ### Read the provided examples In [`c-abi-examples/`](c-abi-examples/) you will find a few different simple examples on how to use the library from C code or in your language of choice by using the C Foreign Function Interface. ### Read the rest of this README To learn how to use all the functionalities of this library, read the rest of the README. It's Zig code so you can't copy it verbatim, but for each function there's a C equivalent in [`cuckoofilter_c.zig`](src/cuckoofilter_c.zig). ### Download binaries or compile it yourself You can download pre-compiled binaries from the Release section on GitHub. To compile the code yourself you need to [install the Zig compiler](https://ziglang.org). Each file in [`c-abi-examples/`](c-abi-examples/) will have comments that will tell you more precisely what you need. Please read the [official Zig documentation](https://ziglang.org/documentation/master/) to learn more about available targets, build modes, static/dynamic linking, etc. Usage ----- ### Quickstart ```zig const std = @import("std"); const hasher = std.hash.Fnv1a_64; const cuckoo = @import("./src/cuckoofilter.zig"); fn fingerprint(x: []const u8) u8 { return x[0]; } pub fn main() !void { const universe_size = 1000000; const memsize = comptime cuckoo.Filter8.size_for(universe_size); var memory: [memsize]u8 align(cuckoo.Filter8.Align) = undefined; var cf = try cuckoo.Filter8.init(memory[0..]); const banana_h = hasher.hash("banana"); const banana_fp = fingerprint("banana"); const apple_h = hasher.hash("apple"); const apple_fp = fingerprint("apple"); _ = try cf.maybe_contains(banana_h, banana_fp); // => false _ = try cf.count(); // => 0 try cf.add(banana_h, banana_fp); _ = try cf.maybe_contains(banana_h, banana_fp); // => true _ = try cf.maybe_contains(apple_h, apple_fp); // => false _ = try cf.count(); // => 1 try cf.remove(banana_h, banana_fp); _ = try cf.maybe_contains(banana_h, banana_fp); // => false _ = try cf.count(); // => 0 } ``` ### Extended example This is also available in [example.zig](example.zig). ```zig const std = @import("std"); const hasher = std.hash.Fnv1a_64; const cuckoo = @import("./src/cuckoofilter.zig"); fn fingerprint8(x: []const u8) u8 { return x[0]; } fn fingerprint32(x: []const u8) u32 { // Just a sample strategy, not suitable for all types // of input. Imagine if you were adding images to the // filter: all fingerprints would be the same because // most formats have a standard header. In that case // you want to make sure to use the actual graphical // data to pluck your fingerprint from. return @bytesToSlice(u32, x[0..@sizeOf(u32)])[0]; } pub fn main() !void { // Assume we want to keep track of max 1 Million items. const universe_size = 1000000; // Let's use Filter8, a filter with 1 byte long // fingerprints and a 3% max *false positive* error rate. // Note: Cuckoo filters cannot produce false negatives. // Error % information: _ = cuckoo.Filter8.MaxError; // ╚═> 3.125e-02 (~0.03, i.e. 3%) _ = cuckoo.Filter16.MaxError; // ╚═> 1.22070312e-04 (~0.0001, i.e. 0.01%) _ = cuckoo.Filter32.MaxError; // ╚═> 9.31322574e-10 (~0.000000001, i.e. 0.0000001%) // First let's calculate how big the filter has to be: const memsize = comptime cuckoo.Filter8.size_for(universe_size); // The value of memsize has to be a power of two and it // is *strongly* recommended to keep the fill rate of a // filter under 80%. size_for() will pad the number for // you automatically and then round up to the closest // power of 2. size_for_exactly() will not apply any // padding before rounding up. // Use capacity() to know how many items a slice of memory // can store for the given filter type. _ = cuckoo.Filter8.capacity(memsize); // => 2097152 // Note: this function will return the theoretical maximum // capacity, without subtracting any padding. It's smart // to adjust your expectations to match how much memory // you have to allocate anyway, but don't get too greedy. // I say `theoretical` because an overfilled filter will // start refusing inserts with a TooFull error. // This is how you allocate static memory for the filter: var memory: [memsize]u8 align(cuckoo.Filter8.Align) = undefined; // Note: the filter benefits from a specific alignment // (which differs from type to type) so you must specify it // when allocating memory. Failing to do so will result in // a comptime error. // Instantiating a filter var cf8 = try cuckoo.Filter8.init(memory[0..]); // // FILTER USAGE // const banana_h = hasher.hash("banana"); const banana_fp = fingerprint8("banana"); const apple_h = hasher.hash("apple"); const apple_fp = fingerprint8("apple"); _ = try cf8.maybe_contains(banana_h, banana_fp); // => false _ = try cf8.count(); // => 0 try cf8.add(banana_h, banana_fp); _ = try cf8.maybe_contains(banana_h, banana_fp); // => true _ = try cf8.maybe_contains(apple_h, apple_fp); // => false _ = try cf8.count(); // => 1 try cf8.remove(banana_h, banana_fp); _ = try cf8.maybe_contains(banana_h, banana_fp); // => false _ = try cf8.count(); // => 0 // The filter can also be used with dynamic memory. // It's up to you to manage that via an allocator. const example_allocator = std.heap.c_allocator; // Don't forget to free the memory afterwards. const memsize32 = comptime cuckoo.Filter32.size_for_exactly(64); var dyn_memory = try example_allocator.alignedAlloc(u8, cuckoo.Filter32.Align, memsize32); defer example_allocator.free(dyn_memory); var dyn_cf32 = try example_allocator.create(cuckoo.Filter32); defer example_allocator.destroy(dyn_cf32); dyn_cf32.* = try cuckoo.Filter32.init(dyn_memory); // When restoring a persisted filter, you should only persist the individual fields // as, for example, .buckets is a slice that points to `dyn_memory` which would be // invalid upon restore (wrong pointer) and just a waste of space when stored. // Upon loading, to reconnect the filter and its `dyn_memory`, use bytesToBuckets. // Here's an example (which is not necessary to make this script work, as we just created // the entire filter): // // dyn_cf32.buckets = cuckoo.Filter32.bytesToBuckets(dyn_memory); // // USAGE FAILURE SCENARIOS // // 1. Adding too many colliding items (because of bad entropy or // because you are adding multiple copies of the same item) const pear_h = hasher.hash("pear"); const pear_fp = fingerprint32("pear"); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); try dyn_cf32.add(pear_h, pear_fp); // No more space for items with equal hash and fp, // next insert will fail. dyn_cf32.add(pear_h, pear_fp) catch |err| switch (err) { error.TooFull => std.debug.warn("yep, too full\n"), else => unreachable, }; // Other inserts that don't collide can still succeed const orange_h = hasher.hash("orange"); const orange_fp = fingerprint32("orange"); try dyn_cf32.add(orange_h, orange_fp); // 2. You can only delete elements that were inserted before. // Trying to delete a non-existing item has a chance of // breaking the filter (makes false negatives possible). // Deleting a non-existing item can either cause the // deletion of another colliding item or fail to find // a matching fingerprint in the filter. In the second // case the filter locks down and returns an error for // all operations, as it is now impossible to know what // the correct state would be. dyn_cf32.remove(0, 0) catch |err| switch (err) { error.Broken => std.debug.warn(".remove, broken\n"), }; _ = dyn_cf32.is_broken(); // => true dyn_cf32.add(orange_fp, orange_fp) catch |err| switch (err) { error.Broken => std.debug.warn(".add, broken\n"), error.TooFull => {}, }; if (dyn_cf32.count()) |_| { std.debug.warn(".count, works\n"); // won't be printed } else |err| switch (err) { error.Broken => std.debug.warn(".count, broken\n") } // Since searching does not mutate the filter, if the item // is found, no error is returned: _ = try dyn_cf32.maybe_contains(orange_h, orange_fp); // => true // But if an item is not found, we don't know if it was wrongly // deleted or not, so the filter has to return an error in order // to ensure that it does not return a false negative response. if (dyn_cf32.maybe_contains(0, 0)) |_| { std.debug.warn(".maybe_contains, works\n"); // won't be printed } else |err| switch (err) { error.Broken => std.debug.warn(".maybe_contains, broken\n") } // You should *NEVER* get into that situation. If you do, it's // a programming error. If your program runs in an environment // where a request that involves the filter might be repeated // (e.g. web servers), mark each request by a unique ID and // keep some kind of commit log to ensure you don't run the // same request twice, as it's semantically wrong to expect // idempotence from Cuckoo filter commands. // 3. Other small errors could be trying to pass to init memory // with the wrong alignment or a wrong buffer size. Try to // use the provided functions (i.e. size_for, size_for_exactly) // to always have your buffers be the right size. You can // also use those functions to reason about your data and even // opt not to use a filter if the tradeoff is not worth it. if (cuckoo.Filter8.init(memory[1..13])) |_| { std.debug.warn(".init, works\n"); // won't be printed } else |err| switch (err) { error.BadLength => std.debug.warn(".init failed, use .size_for()!\n") } // // FIXING TOO FULL // // Filter8 and Filter16 have 4 element-wide buckets, // while Filter32 has 2 element-wide buckets. // Each fingerprint has two buckets that can be used to // house it. This means that you can have, respectively, // up to 8 (F8, F16) and 4 (F32) collisions/copies before both // buckets fill completely and you get TooFull. In practice, // you get an extra chance because of how filters work internally. // There's a special slot that houses a single fingerprint that // could not find space in one of its 2 candidate slots. // The problem is that once that "safety" slot is filled, the // filter becomes much more succeptible to collisions and is forced // to return TooFull when in fact it could try to make space. // If you are also deleting elements from the filter, and // not just adding them, this is what you can do to try and // recover from that situation. // Returns true if the safety slot is occupied. var bad_situation = dyn_cf32.is_toofull(); // Note that you might not have ever received a TooFull error for // this function to return true. In our previous example with // dyn_cf32, it took us 5 insertions to obtain a TooFull error. // This function would return true after 4. // Try to fix the situation: if (bad_situation) { dyn_cf32.fix_toofull() catch |err| switch (err) { error.Broken => {}, error.TooFull => {}, }; } // With this function you can only fix TooFull, not Broken. // If fix_toofull returns TooFull, it means that it failed. // In practice you will need to free more elements before // being able to fix the situation, but in theory calling // the function multiple times might eventually fix the // situation (i.e. it can make progress each call). // That said, going back to practical usage, you are probably // in a problematic situation when it gets to that point. // To ensure you never have to deal with these problems, // make sure you: // (1) Never overfill/undersize a filter. // (2) Get entropy right for the fingerprinting function. // // A trick to get (2) right is to pluck it not out of the // original element, but out of hash2(element). Just make sure // you use a different hasing function, independent from the // fitst one, otherwise you're going to still end up with too // little entropy, and be aware of the increased computational // cost. Secondary hashing might be worth it for semi-strucutred // data where you might find it hard to know if you're plucking // "variable" data or part of the structure (e.g. JSON data), // since the latter is bound to have lower entropy. // // PRNG Stuff // // Cuckoo Filters need a random number generator to decide which // fingerprint to evict when a given bucket pair is full. This // library provides a default implementation that uses the Zig // standard library's Xoroshiro implementation, seeded by default to 42. // If your application has short-lived sessions, a static seed won't be // good enough, as it will basically result in giving out the same // number over and over again, similarly to what is shown in that one // dilbert strip. To fix that use seed_default_prng: var buf: [8]u8 = undefined; try std.crypto.randomBytes(buf[0..]); const seed = std.mem.readIntSliceLittle(u64, buf[0..8]); cuckoo.seed_default_prng(seed); // Additionally, you might also want to provide your own PRNG // implementation, either because you have specific needs (CSPRNG) or // because you might want to make the filter fully deterministic and thus // need to be able to persist and restore the PRNG's state. // You can customize the PRNG of each filter by providing an appropriate // function pointer: dyn_cf32.rand_fn = DilbertRandom; // From now on `dyn_cf32` will stop using the default implementation // (shared by default by all filters) and will instead only use the // provided function. If you use this functionality, *make sure to // set the function pointer again when loading the filter from disk*. // If you're fine with the default implementation and want more control // than just seeding, use .get_default_prng_state() and // .set_default_prng_state(), but beware that you are modifying a // "singleton" struct used by all filters. If you are in a multi-threaded // context this might cause problems if you are executing // .add / .delete / .fix_toofull and altering the prng singleton at the // same time. In that case you will have to customize .rand_fn } fn DilbertRandom() u1 { return 1; } ``` This will output: ``` yep, too full .remove, broken .add, broken .count, broken .maybe_contains, broken .init failed, use .size_for()! ``` Planned Features ---------------- - (maybe) Full-fledged wrappers for the most common languages? It's not that hard to get there given where I got to with `c-abi-examples`. License ------- MIT License Copyright (c) 2019 Loris Cro Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/c-abi-examples/node_example.js
var ref = require('ref'); var ffi = require('ffi'); var Struct = require('ref-struct'); var ArrayType = require('ref-array'); // TODO: change line 19 to refelct the correct path where libcuckoofilter_c is stored. // On macOS dynamic libraries have the .dylib extension. Windows has .dll and linux has .so // You can obtain libcuckoofilter_c.xxx.{dynlib, so, dll} either by downloading it from the // latest Release on GitHub or by compiling the library using the Zig compiler: // // $ zig build-lib -dynamic --release-fast src/cuckoofilter_c.zig // // On macOS this currently produces a dylib file that ld doesn't like so I had to use gcc // as follows (the first command produces cuckoofilter_c.o, which is used by the second command): // // $ zig build-obj --release-fast src/cuckoofilter_c.zig // $ gcc -dynamiclib -o libcuckoofilter_c.0.0.0.dylib cuckoofilter_c.o // const dynamic_library_path = 'libcuckoofilter_c.0.0.0'; var ByteArray = ArrayType('uint8'); var IntPtr = ref.refType('int'); // Just importing the bare minimum functionality to make this example script work. var Filter8 = Struct({ 'cf': ArrayType("uint8", 56) }); var Filter8Ptr = ref.refType(Filter8); var Cuckoo = ffi.Library(dynamic_library_path, { "cf_init8": [ 'int', [ByteArray, 'int', Filter8Ptr] ], "cf_add8": [ 'int', [Filter8Ptr, 'uint64', 'uint64'] ], "cf_maybe_contains8": [ 'int', [Filter8Ptr, 'uint64', 'uint64', IntPtr] ], }); // Allocate the memory var cf8 = ref.alloc(Filter8); var memory = new ByteArray(1024); // Initialize the filter var err = Cuckoo.cf_init8(memory, 1024, cf8); if (err) console.log(err); // Add a fingerprint err = Cuckoo.cf_add8(cf8, 0, 42); if (err) console.log(err); // Search for it var found = ref.alloc('int'); err = Cuckoo.cf_maybe_contains8(cf8, 0, 42, found); if (err) console.log(err); console.log("Found? ", found.deref()); // Search non-existing item err = Cuckoo.cf_maybe_contains8(cf8, 0, 43, found); if (err) console.log(err); console.log("Found? ", found.deref());
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/c-abi-examples/python_example.py
from cffi import FFI # On macOS dynamic libraries have the .dylib extension. Windows has .dll and linux has .so # You can obtain libcuckoofilter_c.xxx.{dylib, so, dll} either by downloading it from the latest Release on GitHub # or by compiling the library using the Zig compiler: # # $ zig build-lib -dynamic --release-fast src/cuckoofilter_c.zig # # TODO: change the next line to the correct path wher libcuckoofilter_c is stored dynamic_library_path = 'path/to/libcuckoofilter_c.0.0.0.dylib' # NOTE: Python's CFFI module also supports compile-time linking to a shared object file, # which is the preferred method over what is shown in this brief example. ffi = FFI() # pycparser unfortunately does nor support directives so # we can't just .read() the headerfile directly, and must # instead copypaste all definitions manually. ffi.cdef(""" typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; typedef long long intmax_t; typedef unsigned long long uintmax_t; struct Filter8 { uint8_t cf[56]; }; struct Filter16 { uint8_t cf[56]; }; struct Filter32 { uint8_t cf[56]; }; void seed_default_prng(uint64_t seed); uintptr_t cf_size_for8(uintptr_t min_capacity); uintptr_t cf_size_for16(uintptr_t min_capacity); uintptr_t cf_size_for32(uintptr_t min_capacity); uintptr_t cf_size_for_exactly8(uintptr_t min_capacity); uintptr_t cf_size_for_exactly16(uintptr_t min_capacity); uintptr_t cf_size_for_exactly32(uintptr_t min_capacity); uintptr_t cf_capacity8(uintptr_t size); uintptr_t cf_capacity16(uintptr_t size); uintptr_t cf_capacity32(uintptr_t size); int cf_init8(uint8_t * memory, uintptr_t size, struct Filter8 * cf); int cf_init16(uint8_t * memory, uintptr_t size, struct Filter16 * cf); int cf_init32(uint8_t * memory, uintptr_t size, struct Filter32 * cf); int cf_count8(struct Filter8 * cf, uintptr_t * res); int cf_count16(struct Filter16 * cf, uintptr_t * res); int cf_count32(struct Filter32 * cf, uintptr_t * res); int cf_maybe_contains8(struct Filter8 * cf, uint64_t hash, uint8_t fp, int * res); int cf_maybe_contains16(struct Filter16 * cf, uint64_t hash, uint16_t fp, int * res); int cf_maybe_contains32(struct Filter32 * cf, uint64_t hash, uint32_t fp, int * res); int cf_remove8(struct Filter8 * cf, uint64_t hash, uint8_t fp); int cf_remove16(struct Filter16 * cf, uint64_t hash, uint16_t fp); int cf_remove32(struct Filter32 * cf, uint64_t hash, uint32_t fp); int cf_add8(struct Filter8 * cf, uint64_t hash, uint8_t fp); int cf_add16(struct Filter16 * cf, uint64_t hash, uint16_t fp); int cf_add32(struct Filter32 * cf, uint64_t hash, uint32_t fp); int cf_is_broken8(struct Filter8 * cf); int cf_is_broken16(struct Filter16 * cf); int cf_is_broken32(struct Filter32 * cf); int cf_is_toofull8(struct Filter8 * cf); int cf_is_toofull16(struct Filter16 * cf); int cf_is_toofull32(struct Filter32 * cf); int cf_fix_toofull8(struct Filter8 * cf); int cf_fix_toofull16(struct Filter16 * cf); int cf_fix_toofull32(struct Filter32 * cf); int cf_restore_memory8(struct Filter8 * cf, uint8_t * memory, uintptr_t memory_len); int cf_restore_memory16(struct Filter16 * cf, uint8_t * memory, uintptr_t memory_len); int cf_restore_memory32(struct Filter32 * cf, uint8_t * memory, uintptr_t memory_len); """) cuckoo = ffi.dlopen(dynamic_library_path) # Instantiate memory for a new filter: cf8 = ffi.new("struct Filter8 *") # Instantiate memory for the filter's buckets: memory = ffi.new("uint8_t[]", 1024) # Initialize the filter: err = cuckoo.cf_init8(memory, 1024, cf8) assert err == 0 # Add a fingerprint: err = cuckoo.cf_add8(cf8, 0, ord('a')) assert err == 0 # Check its presence: found = ffi.new("int *") err = cuckoo.cf_maybe_contains8(cf8, 0, ord('a'), found) assert err == 0 print("Found?", found[0]) # => 1 # Non existing item err = cuckoo.cf_maybe_contains8(cf8, 0, 0, found) assert err == 0 print("Found?", found[0]) # => 0
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/c-abi-examples/go_example.go
package main // TODO: update lines 12 and 13 with the path where libcuckoofilter_c.{dynlib, so, dll} is stored. // eg (when the file is saved in the repo's root directory (i.e. one level above where this file lives)): // #cgo CFLAGS: -I ../ // #cgo LDFLAGS: -L ../ -lcuckoofilter_c.0.0.0 // // On macOS dynamic libraries have the .dylib extension. Windows has .dll and linux has .so // You can obtain libcuckoofilter_c.xxx.{dynlib, so, dll} either by downloading it from the // latest Release on GitHub or by compiling the library using the Zig compiler: // // $ zig build-lib -dynamic --release-fast src/cuckoofilter_c.zig // // On macOS this currently produces a dylib file that ld doesn't like so I had to use gcc // as follows: // // $ zig build-obj --release-fast src/cuckoofilter_c.zig // $ gcc -dynamiclib -o libcuckoofilter_c.0.0.0.dylib cuckoofilter_c.o // /* #cgo CFLAGS: -I ../ #cgo LDFLAGS: -L ../ -l cuckoofilter_c.0.0.0 #include <stdint.h> #include "cuckoofilter_c.h" */ import "C" import ( "fmt" ) func main() { var err C.int var found C.int // Allocate the memory cf8 := C.struct_Filter8{} memory := make([]C.uint8_t, 1024) // Initialize the filter err = C.cf_init8(&memory[0], 1024, &cf8) if err != 0 { fmt.Println("Error!") } // Add a fingerprint err = C.cf_add8(&cf8, 0, 'a') if err != 0 { fmt.Println("Error!") } // Search for it err = C.cf_maybe_contains8(&cf8, 0, 'a', &found) if err != 0 { fmt.Println("Error!") } fmt.Printf("Found? %d\n", found) // Search non-existing item err = C.cf_maybe_contains8(&cf8, 0, 'b', &found) if err != 0 { fmt.Println("Error!") } fmt.Printf("Found? %d\n", found) }
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/c-abi-examples/cuckoofilter_c.h
#ifndef CUCKOOFILTER_C_H #define CUCKOOFILTER_C_H #include <stdint.h> #ifdef __cplusplus #define CUCKOOFILTER_C_EXTERN_C extern "C" #else #define CUCKOOFILTER_C_EXTERN_C #endif struct Filter8 { uint8_t cf[56]; }; struct Filter16 { uint8_t cf[56]; }; struct Filter32 { uint8_t cf[56]; }; CUCKOOFILTER_C_EXTERN_C void seed_default_prng(uint64_t seed); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for8(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for16(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for32(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for_exactly8(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for_exactly16(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_size_for_exactly32(uintptr_t min_capacity); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_capacity8(uintptr_t size); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_capacity16(uintptr_t size); CUCKOOFILTER_C_EXTERN_C uintptr_t cf_capacity32(uintptr_t size); CUCKOOFILTER_C_EXTERN_C int cf_init8(uint8_t * memory, uintptr_t size, struct Filter8 * cf); CUCKOOFILTER_C_EXTERN_C int cf_init16(uint8_t * memory, uintptr_t size, struct Filter16 * cf); CUCKOOFILTER_C_EXTERN_C int cf_init32(uint8_t * memory, uintptr_t size, struct Filter32 * cf); CUCKOOFILTER_C_EXTERN_C int cf_count8(struct Filter8 * cf, uintptr_t * res); CUCKOOFILTER_C_EXTERN_C int cf_count16(struct Filter16 * cf, uintptr_t * res); CUCKOOFILTER_C_EXTERN_C int cf_count32(struct Filter32 * cf, uintptr_t * res); CUCKOOFILTER_C_EXTERN_C int cf_maybe_contains8(struct Filter8 * cf, uint64_t hash, uint8_t fp, int * res); CUCKOOFILTER_C_EXTERN_C int cf_maybe_contains16(struct Filter16 * cf, uint64_t hash, uint16_t fp, int * res); CUCKOOFILTER_C_EXTERN_C int cf_maybe_contains32(struct Filter32 * cf, uint64_t hash, uint32_t fp, int * res); CUCKOOFILTER_C_EXTERN_C int cf_remove8(struct Filter8 * cf, uint64_t hash, uint8_t fp); CUCKOOFILTER_C_EXTERN_C int cf_remove16(struct Filter16 * cf, uint64_t hash, uint16_t fp); CUCKOOFILTER_C_EXTERN_C int cf_remove32(struct Filter32 * cf, uint64_t hash, uint32_t fp); CUCKOOFILTER_C_EXTERN_C int cf_add8(struct Filter8 * cf, uint64_t hash, uint8_t fp); CUCKOOFILTER_C_EXTERN_C int cf_add16(struct Filter16 * cf, uint64_t hash, uint16_t fp); CUCKOOFILTER_C_EXTERN_C int cf_add32(struct Filter32 * cf, uint64_t hash, uint32_t fp); CUCKOOFILTER_C_EXTERN_C int cf_is_broken8(struct Filter8 * cf); CUCKOOFILTER_C_EXTERN_C int cf_is_broken16(struct Filter16 * cf); CUCKOOFILTER_C_EXTERN_C int cf_is_broken32(struct Filter32 * cf); CUCKOOFILTER_C_EXTERN_C int cf_is_toofull8(struct Filter8 * cf); CUCKOOFILTER_C_EXTERN_C int cf_is_toofull16(struct Filter16 * cf); CUCKOOFILTER_C_EXTERN_C int cf_is_toofull32(struct Filter32 * cf); CUCKOOFILTER_C_EXTERN_C int cf_fix_toofull8(struct Filter8 * cf); CUCKOOFILTER_C_EXTERN_C int cf_fix_toofull16(struct Filter16 * cf); CUCKOOFILTER_C_EXTERN_C int cf_fix_toofull32(struct Filter32 * cf); CUCKOOFILTER_C_EXTERN_C int cf_restore_memory8(struct Filter8 * cf, uint8_t * memory, uintptr_t memory_len); CUCKOOFILTER_C_EXTERN_C int cf_restore_memory16(struct Filter16 * cf, uint8_t * memory, uintptr_t memory_len); CUCKOOFILTER_C_EXTERN_C int cf_restore_memory32(struct Filter32 * cf, uint8_t * memory, uintptr_t memory_len); #endif
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/c-abi-examples/c_example.c
#import <stdio.h> #import "cuckoofilter_c.h" // // Compile using: // // GCC: // $ gcc -o c_example c_example.c path/to/cuckoofilter_c.o // // Zig: // $ zig build-exe --c-source c_example.c --library c --object path/to/cuckoofilter_c.o // // You can obtain cuckoofilter_c.o either by downloading it from the latest Release on GitHub // or by compiling the library using the Zig compiler: // // $ zig build-obj --release-fast src/cuckoofilter_c.zig // int main(int argc, char const *argv[]) { int err; int found; unsigned char memory[1024]; struct Filter8 cf; err = cf_init8(memory, 1024, &cf); if (err != 0) { printf("Error!\n"); } // Search for the item hash = 0, fp = 'a' err = cf_maybe_contains8(&cf, 0, 'a', &found); if (err != 0) { printf("Error!\n"); } printf("%d\n", found); // Add the item err = cf_add8(&cf, 0, 'a'); if (err != 0) { printf("Error!\n"); } // Search it again err = cf_maybe_contains8(&cf, 0, 'a', &found); if (err != 0) { printf("Error!\n"); } printf("%d\n", found); return 0; }
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/src/cuckoofilter.zig
const builtin = @import("builtin"); const std = @import("std"); const testing = std.testing; const FREE_SLOT = 0; // Use the provided function to re-seed the default PRNG implementation. var xoro = std.rand.Xoroshiro128.init(42); pub fn seed_default_prng(seed: u64) void { xoro.seed(seed); } // If you want to read the state of the default PRNG impl: pub fn get_default_prng_state() [2]u64 { return xoro.s; } // If you want to set the state of the default PRNG impl: pub fn set_default_prng_state(s: [2]u64) void { xoro.s = s; } // Default PRNG implementation. // By overriding .rand_fn you can provide your own custom PRNG implementation. // Useful in adversarial situations (CSPRNG) or when you need deterministic behavior // from the filter, as it requires to be able to save and restore the PRNG's state. // You can use Filter<X>.RandomFn to see the function type you need to fulfill. fn XoroRandFnImpl (comptime T: type) type { return struct { fn random () T { return xoro.random.int(T); } }; } // Supported CuckooFilter implementations. // Bucket size is chosen mainly to keep the bucket 64bit word-sized, or under. // This way reading a bucket requires a single memory fetch. // Filter8 does not have 8-fp wide buckets to keep the error rate under 3%, // as this is the cutoff point where Cuckoo Filters become more space-efficient // than Bloom. We also enforce memory alignment. pub const Filter8 = CuckooFilter(u8, 4); pub const Filter16 = CuckooFilter(u16, 4); pub const Filter32 = CuckooFilter(u32, 2); fn CuckooFilter(comptime Tfp: type, comptime buckSize: usize) type { return struct { homeless_fp: Tfp, homeless_bucket_idx: usize, buckets: [] align(Align) Bucket, fpcount: usize, broken: bool, rand_fn: ?RandomFn, pub const FPType = Tfp; pub const Align = std.math.min(@alignOf(usize), @alignOf(@IntType(false, buckSize * @typeInfo(Tfp).Int.bits))); pub const MaxError = 2.0 * @intToFloat(f32, buckSize) / @intToFloat(f32, 1 << @typeInfo(Tfp).Int.bits); pub const RandomFn = fn () BucketSizeType; const BucketSizeType = @IntType(false, comptime std.math.log2(buckSize)); const Bucket = [buckSize]Tfp; const MinSize = @sizeOf(Tfp) * buckSize * 2; const Self = @This(); const ScanMode = enum { Set, Force, Delete, Search, }; pub fn size_for(min_capacity: usize) usize { return size_for_exactly(min_capacity + @divTrunc(min_capacity, 5)); } pub fn size_for_exactly(min_capacity: usize) usize { var res = std.math.pow(usize, 2, std.math.log2(min_capacity)); if (res != min_capacity) res <<= 1; const requested_size = res * @sizeOf(Tfp); return if (MinSize > requested_size) MinSize else requested_size; } pub fn capacity(size: usize) usize { return size / @sizeOf(Tfp); } // Use bytesToBuckets when you have persisted the filter and need to restore it. // This will allow to cast back your bytes slice in the correct type for the .buckets // property. Make sure you still have the right alignment when loading the data back! pub fn bytesToBuckets(memory: [] align(Align) u8) ![] align(Align) Bucket { const not_pow2 = memory.len != std.math.pow(usize, 2, std.math.log2(memory.len)); if (not_pow2 or memory.len < MinSize) return error.BadLength; return @bytesToSlice(Bucket, memory); } pub fn init(memory: [] align(Align) u8) !Self { for (memory) |*x| x.* = 0; return Self { .homeless_fp = FREE_SLOT, .homeless_bucket_idx = undefined, .buckets = try bytesToBuckets(memory), .fpcount = 0, .broken = false, .rand_fn = null, }; } pub fn count(self: *Self) !usize { return if (self.broken) error.Broken else self.fpcount; } pub fn maybe_contains(self: *Self, hash: u64, fingerprint: Tfp) !bool { const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (fp == self.scan(bucket_idx, fp, .Search, FREE_SLOT)) return true; // Try alt bucket const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (fp == self.scan(alt_bucket_idx, fp, .Search, FREE_SLOT)) return true; // Try homeless slot if (self.is_homeless_fp(bucket_idx, alt_bucket_idx, fp)) return true else return if (self.broken) error.Broken else false; } pub fn remove(self: *Self, hash: u64, fingerprint: Tfp) !void { if (self.broken) return error.Broken; const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (fp == self.scan(bucket_idx, fp, .Delete, FREE_SLOT)) { self.fpcount -= 1; return; } // Try alt bucket const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (fp == self.scan(alt_bucket_idx, fp, .Delete, FREE_SLOT)) { self.fpcount -= 1; return; } // Try homeless slot if (self.is_homeless_fp(bucket_idx, alt_bucket_idx, fp)){ self.homeless_fp = FREE_SLOT; self.fpcount -= 1; return; } // Oh no... self.broken = true; return error.Broken; } pub fn add(self: *Self, hash: u64, fingerprint: Tfp) !void { if (self.broken) return error.Broken; const fp = if (FREE_SLOT == fingerprint) 1 else fingerprint; const bucket_idx = hash & (self.buckets.len - 1); // Try primary bucket if (FREE_SLOT == self.scan(bucket_idx, FREE_SLOT, .Set, fp)) { self.fpcount += 1; return; } // If too tull already, try to add the fp to the secondary slot without forcing const alt_bucket_idx = self.compute_alt_bucket_idx(bucket_idx, fp); if (FREE_SLOT != self.homeless_fp) { if (FREE_SLOT == self.scan(alt_bucket_idx, FREE_SLOT, .Set, fp)) { self.fpcount += 1; return; } else return error.TooFull; } // We are now willing to force the insertion self.homeless_bucket_idx = alt_bucket_idx; self.homeless_fp = fp; self.fpcount += 1; var i : usize = 0; while (i < 500) : (i += 1) { self.homeless_bucket_idx = self.compute_alt_bucket_idx(self.homeless_bucket_idx, self.homeless_fp); self.homeless_fp = self.scan(self.homeless_bucket_idx, FREE_SLOT, .Force, self.homeless_fp); if (FREE_SLOT == self.homeless_fp) return; } // If we went over the while loop, now the homeless slot is occupied. } pub fn is_broken(self: *Self) bool { return self.broken; } pub fn is_toofull(self: *Self) bool { return FREE_SLOT != self.homeless_fp; } pub fn fix_toofull(self: *Self) !void { if (FREE_SLOT == self.homeless_fp) return else { const homeless_fp = self.homeless_fp; self.homeless_fp = FREE_SLOT; try self.add(self.homeless_bucket_idx, homeless_fp); if (FREE_SLOT != self.homeless_fp) return error.TooFull; } } inline fn is_homeless_fp(self: *Self, bucket_idx: usize, alt_bucket_idx: usize, fp: Tfp) bool { const same_main = (self.homeless_bucket_idx == bucket_idx); const same_alt = (self.homeless_bucket_idx == alt_bucket_idx); const same_fp = (self.homeless_fp == fp); return (same_fp and (same_main or same_alt)); } inline fn compute_alt_bucket_idx(self: *Self, bucket_idx: usize, fp: Tfp) usize { const fpSize = @sizeOf(Tfp); const FNV_OFFSET = 14695981039346656037; const FNV_PRIME = 1099511628211; // Note: endianess const bytes = @ptrCast(*const [fpSize] u8, &fp).*; var res: usize = FNV_OFFSET; comptime var i = 0; inline while (i < fpSize) : (i += 1) { res ^= bytes[i]; res *%= FNV_PRIME; } return (bucket_idx ^ res) & (self.buckets.len - 1); } inline fn scan(self: *Self, bucket_idx: u64, fp: Tfp, comptime mode: ScanMode, val: Tfp) Tfp { comptime var i = 0; // Search the bucket var bucket = &self.buckets[bucket_idx]; inline while (i < buckSize) : (i += 1) { if (bucket[i] == fp) { switch (mode) { .Search => {}, .Delete => bucket[i] = FREE_SLOT, .Set => bucket[i] = val, .Force => bucket[i] = val, } return fp; } } switch (mode) { .Search => return FREE_SLOT, .Delete => return FREE_SLOT, .Set => return 1, .Force => { // We did not find any free slot, so we must now evict. const slot = if (self.rand_fn) |rfn| rfn() else XoroRandFnImpl(BucketSizeType).random(); const evicted = bucket[slot]; bucket[slot] = val; return evicted; }, } } }; } test "Hx == (Hy XOR hash(fp))" { var memory: [1<<20]u8 align(Filter8.Align) = undefined; var cf = Filter8.init(memory[0..]) catch unreachable; testing.expect(0 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(0, 'x'), 'x')); testing.expect(1 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(1, 'x'), 'x')); testing.expect(42 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(42, 'x'), 'x')); testing.expect(500 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(500, 'x'), 'x')); testing.expect(5000 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(5000, 'x'), 'x')); testing.expect(10585 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(10585, 'x'), 'x')); testing.expect(10586 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(10586, 'x'), 'x')); testing.expect(18028 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx(18028, 'x'), 'x')); testing.expect((1<<15) - 1 == cf.compute_alt_bucket_idx(cf.compute_alt_bucket_idx((1<<15) - 1, 'x'), 'x')); } fn test_not_broken(cf: var) void { testing.expect(false == cf.maybe_contains(2, 'a') catch unreachable); testing.expect(0 == cf.count() catch unreachable); cf.add(2, 'a') catch unreachable; testing.expect(cf.maybe_contains(2, 'a') catch unreachable); testing.expect(false == cf.maybe_contains(0, 'a') catch unreachable); testing.expect(false == cf.maybe_contains(1, 'a') catch unreachable); testing.expect(1 == cf.count() catch unreachable); cf.remove(2, 'a') catch unreachable; testing.expect(false == cf.maybe_contains(2, 'a') catch unreachable); testing.expect(0 == cf.count() catch unreachable); } test "is not completely broken" { var memory: [16]u8 align(Filter8.Align) = undefined; var cf = Filter8.init(memory[0..]) catch unreachable; test_not_broken(&cf); } const Version = struct { Tfp: type, buckLen: usize, cftype: type, }; const SupportedVersions = []Version { Version { .Tfp = u8, .buckLen = 4, .cftype = Filter8}, Version { .Tfp = u16, .buckLen = 4, .cftype = Filter16}, Version { .Tfp = u32, .buckLen = 2, .cftype = Filter32}, }; test "generics are not completely broken" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; test_not_broken(&cf); } } test "too full when adding too many copies" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; var i: usize = 0; while (i < v.buckLen * 2) : (i += 1) { cf.add(0, 1) catch unreachable; } testing.expect(!cf.is_toofull()); // The first time we go over-board we can still occupy // the homeless slot, so this won't fail: cf.add(0, 1) catch unreachable; testing.expect(cf.is_toofull()); // We now are really full. testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); testing.expectError(error.TooFull, cf.add(0, 1)); testing.expect(cf.is_toofull()); i = 0; while (i < v.buckLen * 2) : (i += 1) { cf.add(2, 1) catch unreachable; } // Homeless slot is already occupied. testing.expectError(error.TooFull, cf.add(2, 1)); testing.expectError(error.TooFull, cf.add(2, 1)); testing.expectError(error.TooFull, cf.add(2, 1)); // Try to fix the situation testing.expect(cf.is_toofull()); // This should fail testing.expectError(error.TooFull, cf.fix_toofull()); // Make it fixable cf.remove(0, 1) catch unreachable; cf.fix_toofull() catch unreachable; testing.expect(!cf.is_toofull()); cf.add(2, 1) catch unreachable; testing.expect(cf.is_toofull()); // Delete now all instances except the homeless one i = 0; while (i < v.buckLen * 2) : (i += 1) { cf.remove(2, 1) catch unreachable; } // Should be able to find the homeless fp testing.expect(cf.maybe_contains(2, 1) catch unreachable); // Delete it and try to find it cf.remove(2, 1) catch unreachable; testing.expect(false == cf.maybe_contains(2, 1) catch unreachable); } } test "properly breaks when misused" { inline for (SupportedVersions) |v| { var memory: [1024]u8 align(v.cftype.Align) = undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; var fp = @intCast(v.Tfp, 1); testing.expectError(error.Broken, cf.remove(2, 1)); testing.expectError(error.Broken, cf.add(2, 1)); testing.expectError(error.Broken, cf.count()); testing.expectError(error.Broken, cf.maybe_contains(2, 1)); } } fn TestSet(comptime Tfp: type) type { const ItemSet = std.hash_map.AutoHashMap(u64, Tfp); return struct { items: ItemSet, false_positives: ItemSet, const Self = @This(); fn init(iterations: usize, false_positives: usize, allocator: *std.mem.Allocator) Self { var item_set = ItemSet.init(allocator); var false_set = ItemSet.init(allocator); return Self { .items = blk: { var i : usize = 0; while (i < iterations) : (i += 1) { var hash = xoro.random.int(u64); while (item_set.contains(hash)) { hash = xoro.random.int(u64); } _ = item_set.put(hash, xoro.random.int(Tfp)) catch unreachable; } break :blk item_set; }, .false_positives = blk: { var i : usize = 0; while (i < false_positives) : (i += 1) { var hash = xoro.random.int(u64); while (item_set.contains(hash) or false_set.contains(hash)) { hash = xoro.random.int(u64); } _ = false_set.put(hash, xoro.random.int(Tfp)) catch unreachable; } break :blk false_set; }, }; } }; } test "small stress test" { const iterations = 60000; const false_positives = 10000; var direct_allocator = std.heap.DirectAllocator.init(); //defer direct_allocator.deinit(); inline for (SupportedVersions) |v| { var test_cases = TestSet(v.Tfp).init(iterations, false_positives, &direct_allocator.allocator); var iit = test_cases.items.iterator(); var fit = test_cases.false_positives.iterator(); //defer test_cases.items.deinit(); //defer test_cases.false_positives.deinit(); // Build an appropriately-sized filter var memory: [v.cftype.size_for(iterations)]u8 align(v.cftype.Align)= undefined; var cf = v.cftype.init(memory[0..]) catch unreachable; // Test all items for presence (should all be false) { iit.reset(); while (iit.next()) |item| { testing.expect(!(cf.maybe_contains(item.key, item.value) catch unreachable)); } } // Add all items (should not fail) { iit.reset(); var iters: usize = 0; while (iit.next()) |item| { testing.expect(iters == cf.count() catch unreachable); cf.add(item.key, item.value) catch unreachable; iters += 1; } testing.expect(iters == cf.count() catch unreachable); } // Test that memory contains the right number of elements { var count: usize = 0; for (@bytesToSlice(v.Tfp, memory)) |byte| { if (byte != 0) { count += 1; } } testing.expect(iterations == count); testing.expect(iterations == cf.count() catch unreachable); } // Test all items for presence (should all be true) { iit.reset(); while (iit.next()) |item| { testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); } } // Delete half the elements and ensure they are not found // (there could be false positives depending on fill lvl) { iit.reset(); const max = @divTrunc(iterations, 2); var count: usize = 0; var false_count: usize = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); cf.remove(item.key, item.value) catch unreachable; testing.expect(iterations - count == cf.count() catch unreachable); if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% iit.reset(); count = 0; false_count = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Test false positive elements { fit.reset(); var false_count: usize = 0; while (fit.next()) |item| { if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Add deleted elements back in and test that all are present { iit.reset(); const max = @divTrunc(iterations, 2); var count: usize = 0; var false_count: usize = 0; while (iit.next()) |item| { count += 1; if (count >= max) break; cf.add(item.key, item.value) catch unreachable; testing.expect(cf.maybe_contains(item.key, item.value) catch unreachable); } } // Test false positive elements (again) { fit.reset(); var false_count: usize = 0; while (fit.next()) |item| { if(cf.maybe_contains(item.key, item.value) catch unreachable) false_count += 1; } testing.expect(false_count < @divTrunc(iterations, 40)); // < 2.5% } // Delete all items { iit.reset(); var iters: usize = 0; while (iit.next()) |item| { cf.remove(item.key, item.value) catch unreachable; iters += 1; } } // Test that memory contains 0 elements { var count: usize = 0; for (@bytesToSlice(v.Tfp, memory)) |fprint| { if (fprint != 0) { count += 1; } } testing.expect(0 == count); testing.expect(0 == cf.count() catch unreachable); } // Test all items for presence (should all be false) { iit.reset(); while (iit.next()) |item| { testing.expect(!(cf.maybe_contains(item.key, item.value) catch unreachable)); } } } }
0
repos/zig-cuckoofilter
repos/zig-cuckoofilter/src/cuckoofilter_c.zig
// // C interface for cucoofilter.zig // const cuckoo = @import("./cuckoofilter.zig"); // CONSTS export const CF_OK: c_int = 0; export const CF_TOOFULL: c_int = 1; export const CF_BROKEN: c_int = 2; export const CF_BADLEN: c_int = 3; export const CF_ALIGN8: usize = cuckoo.Filter8.Align; export const CF_ALIGN16: usize = cuckoo.Filter16.Align; export const CF_ALIGN32: usize = cuckoo.Filter32.Align; export const CF_MAXERR8: f32 = cuckoo.Filter8.MaxError; export const CF_MAXERR16: f32 = cuckoo.Filter16.MaxError; export const CF_MAXERR32: f32 = cuckoo.Filter32.MaxError; export const Filter8 = extern struct { cf: [@sizeOf(cuckoo.Filter8)]u8 }; export const Filter16 = extern struct { cf: [@sizeOf(cuckoo.Filter16)]u8 }; export const Filter32 = extern struct { cf: [@sizeOf(cuckoo.Filter32)]u8 }; // seed_default_prng export fn seed_default_prng(seed: u64) void { cuckoo.seed_default_prng(seed); } // get_default_rng_state export fn get_default_prng_state() [2]u64 { return cuckoo.get_default_prng_state(); } // set_default_rng_state export fn set_default_prng_state(s: [2]u64) void { cuckoo.set_default_prng_state(s); } // size_for export fn cf_size_for8(min_capacity: usize) usize { return cuckoo.Filter8.size_for(min_capacity); } export fn cf_size_for16(min_capacity: usize) usize { return cuckoo.Filter16.size_for(min_capacity); } export fn cf_size_for32(min_capacity: usize) usize { return cuckoo.Filter32.size_for(min_capacity); } // size_for_exactly export fn cf_size_for_exactly8(min_capacity: usize) usize { return cuckoo.Filter8.size_for_exactly(min_capacity); } export fn cf_size_for_exactly16(min_capacity: usize) usize { return cuckoo.Filter16.size_for_exactly(min_capacity); } export fn cf_size_for_exactly32(min_capacity: usize) usize { return cuckoo.Filter32.size_for_exactly(min_capacity); } // capacity export fn cf_capacity8(size: usize) usize { return cuckoo.Filter8.capacity(size); } export fn cf_capacity16(size: usize) usize { return cuckoo.Filter16.capacity(size); } export fn cf_capacity32(size: usize) usize { return cuckoo.Filter32.capacity(size); } // init export fn cf_init8(memory: [*]u8, size: usize, cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter8.init(@alignCast(cuckoo.Filter8.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_init16(memory: [*]u8, size: usize, cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter16.init(@alignCast(cuckoo.Filter16.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_init32(memory: [*]u8, size: usize, cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.* = cuckoo.Filter32.init(@alignCast(cuckoo.Filter32.Align, memory)[0..size]) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } // count export fn cf_count8(cf: *Filter8, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_count16(cf: *Filter16, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_count32(cf: *Filter32, res: *usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); res.* = cf_ptr.count() catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } // maybe_contains export fn cf_maybe_contains8(cf: *Filter8, hash: u64, fp: u8, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } export fn cf_maybe_contains16(cf: *Filter16, hash: u64, fp: u16, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } export fn cf_maybe_contains32(cf: *Filter32, hash: u64, fp: u32, res: *c_int) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); res.* = @boolToInt(cf_ptr.maybe_contains(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }); return CF_OK; } // remove export fn cf_remove8(cf: *Filter8, hash: u64, fp: u8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_remove16(cf: *Filter16, hash: u64, fp: u16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_remove32(cf: *Filter32, hash: u64, fp: u32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.remove(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, }; return CF_OK; } // add export fn cf_add8(cf: *Filter8, hash: u64, fp: u8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } export fn cf_add16(cf: *Filter16, hash: u64, fp: u16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } export fn cf_add32(cf: *Filter32, hash: u64, fp: u32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.add(hash, fp) catch |err| switch (err) { error.Broken => return CF_BROKEN, error.TooFull => return CF_TOOFULL, }; return CF_OK; } // is_broken export fn cf_is_broken8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } export fn cf_is_broken16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } export fn cf_is_broken32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); return @boolToInt(cf_ptr.is_broken()); } // is_toofull export fn cf_is_toofull8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } export fn cf_is_toofull16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } export fn cf_is_toofull32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); return @boolToInt(cf_ptr.is_toofull()); } // fix_toofull export fn cf_fix_toofull8(cf: *Filter8) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_fix_toofull16(cf: *Filter16) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } export fn cf_fix_toofull32(cf: *Filter32) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.fix_toofull() catch |err| switch (err) { error.TooFull => return CF_TOOFULL, error.Broken => return CF_BROKEN, }; return CF_OK; } // To persist a filter you simply need to save the struct's bytes and the its relative buckets // (referred to as `memory` throughout the documentation). The struct contains a pointer // to its `memory` which would not match when loading the filter back again, so use this // function to properly restore it. export fn cf_restore_memory8(cf: *Filter8, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter8, @alignCast(@alignOf(cuckoo.Filter8), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter8.bytesToBuckets(@alignCast(CF_ALIGN8, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_restore_memory16(cf: *Filter16, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter16, @alignCast(@alignOf(cuckoo.Filter16), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter16.bytesToBuckets(@alignCast(CF_ALIGN16, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; } export fn cf_restore_memory32(cf: *Filter32, memory: [*]u8, memory_len: usize) c_int { var cf_ptr = @ptrCast(*cuckoo.Filter32, @alignCast(@alignOf(cuckoo.Filter32), &(cf.*.cf))); cf_ptr.buckets = cuckoo.Filter32.bytesToBuckets(@alignCast(CF_ALIGN32, memory[0..memory_len])) catch |err| switch (err) { error.BadLength => return CF_BADLEN, }; return CF_OK; }
0
repos
repos/rclzig/CONTRIBUTING.md
# Contributing to rclzig Here are a few ways you can contribute to the project: 1. Report bugs by opening an issue on GitHub. Be as detailed as you can. Provide information about your system (e.g. operating system, version of rclzig, version of dependencies, etc). Provide a [short, self contained, correct, example](http://sscce.org/) for reproducing the bug. 2. Open a pull request! Maybe you have an idea about how to fix an issue that was reported. Opening a pull request to fix the issue is a great way to contribute! Keep the changes contained in each pull request focused on fixing one issue at a time. This helps make the pull request easier to review and more likely to be merged. Adding a test to verify your changes are correct is greatly appreciated. ## License notice Any contribution that you make to this repository will be under the Apache 2 License, as dictated by that [license](http://www.apache.org/licenses/LICENSE-2.0.html): ~~~ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. ~~~
0
repos
repos/rclzig/README.md
# rclzig A [ROS 2](https://docs.ros.org/en/rolling/index.html) client library in the [Zig programming language](https://ziglang.org/). ## Features * TODO ## Why? This project was created as a personal way to learn Zig. I was intrigued by the features Zig has to offer (e.g. simple, zero-dependency drop-in replacement for C/C++, cross-compilation out-of-the-box). As an exercise, I challenged myself to integrate the language with ROS 2 and this is the result. ## Should I use this in production? No, probably not. Zig is a very young language (still pre-1.0 release) and not stable. The same applies for rclzig. ## Okay, how can I use rclzig? ### Install dependencies * [Install ROS 2](https://docs.ros.org/en/rolling/Installation.html). * [Install Zig](https://ziglang.org/download/) ### Build 1. Clone this repository git clone https://github.com/jacobperron/rclzig.git 1. Source your ROS 2 installation, e.g. ROS Galactic: source /opt/ros/galactic/setup.bash 1. Build: cd rclzig zig build 1. Optionally, run tests: zig build test ### Try the examples Run the talker: zig build talker In a second shell, run the listener: zig build listener ### Build your own package TODO ## Excellent! How can I contribute? See [CONTRIBUTING.md](CONTRIBUTING.md). ## References Here are some nice resource for learning Zig: * [ziglearn.org](https://ziglearn.org/) is a good starting place. * [Zig's "In-depth overview"](https://ziglang.org/learn/overview/) supplements ziglearn.org very well. * [Zig API reference](https://ziglang.org/documentation/master) * These ["zig build explained"](https://zig.news/xq/zig-build-explained-part-1-59lf) blog posts provide good info about the build system. Part 2 demonstrates how to build C/C++ code from zig. * Jumping straight into the [source code for Zig](https://github.com/ziglang/zig) can also be enlightening.
0
repos
repos/rclzig/build.zig
const std = @import("std"); /// Link a single ament C package. fn amentTargetCDependencies(allocator: *std.mem.Allocator, exe: *std.build.LibExeObjStep, package_names: []const []const u8) void { _ = allocator; const ament_env = std.os.getenv("AMENT_PREFIX_PATH"); if (ament_env) |ament_prefix| { var ament_prefix_iterator = std.mem.tokenize(u8, ament_prefix, ":"); while (ament_prefix_iterator.next()) |prefix| { // TODO(jacobperron): This assumption is wrong if packages install their headers to a subdirectory const include_dir = std.fmt.allocPrint(allocator, "{s}/include", .{prefix}) catch |err| { std.log.err("{e}\n", .{err}); return; }; defer allocator.free(include_dir); exe.addIncludeDir(include_dir); const lib_dir = std.fmt.allocPrint(allocator, "{s}/lib", .{prefix}) catch |err| { std.log.err("{e}\n", .{err}); return; }; defer allocator.free(lib_dir); exe.addLibPath(lib_dir); } } else { std.log.warn("AMENT_PREFIX_PATH is not set\n", .{}); } exe.linkSystemLibrary("c"); for (package_names) |package_name| { exe.linkSystemLibraryName(package_name); } } pub fn build(b: *std.build.Builder) void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const rcl_dependencies = [_][]const u8{ "rcl", "rcutils", "rmw", }; const std_msgs_dependencies = [_][]const u8{ "std_msgs__rosidl_typesupport_c", "std_msgs__rosidl_generator_c", "rosidl_runtime_c", }; const rclzig_pkg = std.build.Pkg{ .name = "rclzig", .path = .{ .path = "./src/rclzig/rclzig.zig" }, }; const std_msgs_pkg = std.build.Pkg{ .name = "std_msgs", .path = .{ .path = "./src/std_msgs/std_msgs.zig" }, }; const std_msgs_lib = b.addStaticLibrary("std_msgs", "src/std_msgs/std_msgs.zig"); std_msgs_lib.setBuildMode(mode); std_msgs_lib.setTarget(target); amentTargetCDependencies(allocator, std_msgs_lib, &std_msgs_dependencies); std_msgs_lib.addPackage(rclzig_pkg); std_msgs_lib.install(); const std_msgs_tests = b.addTest("src/std_msgs/std_msgs.zig"); std_msgs_tests.setBuildMode(mode); amentTargetCDependencies(allocator, std_msgs_tests, &std_msgs_dependencies); const rclzig_lib = b.addStaticLibrary("rclzig", "src/rclzig/rclzig.zig"); rclzig_lib.setBuildMode(mode); rclzig_lib.setTarget(target); amentTargetCDependencies(allocator, rclzig_lib, &rcl_dependencies); rclzig_lib.install(); const rclzig_tests = b.addTest("src/rclzig/rclzig.zig"); rclzig_tests.setBuildMode(mode); amentTargetCDependencies(allocator, rclzig_tests, &rcl_dependencies); amentTargetCDependencies(allocator, rclzig_tests, &std_msgs_dependencies); rclzig_tests.addPackage(std_msgs_pkg); const talker_exe = b.addExecutable("talker", "src/examples/talker.zig"); talker_exe.setTarget(target); talker_exe.setBuildMode(mode); talker_exe.addPackage(rclzig_pkg); talker_exe.addPackage(std_msgs_pkg); amentTargetCDependencies(allocator, talker_exe, &rcl_dependencies); amentTargetCDependencies(allocator, talker_exe, &std_msgs_dependencies); talker_exe.install(); const talker_cmd = talker_exe.run(); talker_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { talker_cmd.addArgs(args); } const talker_step = b.step("talker", "Run the talker example"); talker_step.dependOn(&talker_cmd.step); const listener_exe = b.addExecutable("listener", "src/examples/listener.zig"); listener_exe.setTarget(target); listener_exe.setBuildMode(mode); listener_exe.addPackage(rclzig_pkg); listener_exe.addPackage(std_msgs_pkg); amentTargetCDependencies(allocator, listener_exe, &rcl_dependencies); amentTargetCDependencies(allocator, listener_exe, &std_msgs_dependencies); listener_exe.install(); const listener_cmd = listener_exe.run(); listener_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { listener_cmd.addArgs(args); } const listener_step = b.step("listener", "Run the listener example"); listener_step.dependOn(&listener_cmd.step); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&rclzig_tests.step); test_step.dependOn(&std_msgs_tests.step); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/context.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rcl.zig").rcl; const RclAllocator = @import("allocator.zig").RclAllocator; const fromRclError = @import("errors.zig").fromRclError; pub const ContextOptions = struct { rcl_options: rcl.rcl_init_options_t, pub fn init(allocator: *RclAllocator) !ContextOptions { var context_options = ContextOptions{ .rcl_options = rcl.rcl_get_zero_initialized_init_options(), }; const init_ret = rcl.rcl_init_options_init(&context_options.rcl_options, allocator.c_allocator); if (init_ret != rcl.RCL_RET_OK) { std.log.err("failed to initialize options\n", .{}); return fromRclError(init_ret); } return context_options; } pub fn deinit(self: *ContextOptions) void { const fini_ret = rcl.rcl_init_options_fini(&self.rcl_options); if (fini_ret != rcl.RCL_RET_OK) { std.log.err("failed to finalize rcl_init_options_t ({})\n", .{fini_ret}); } } }; pub const Context = struct { rcl_context: rcl.rcl_context_t, pub fn init(argv: []const []const u8, options: ContextOptions) !Context { var context = Context{ .rcl_context = rcl.rcl_get_zero_initialized_context(), }; const rcl_ret = rcl.rcl_init(@intCast(c_int, argv.len), @ptrToInt(argv.ptr), &options.rcl_options, &context.rcl_context); if (rcl_ret != rcl.RCL_RET_OK) { return fromRclError(rcl_ret); } return context; } pub fn deinit(self: *Context) void { if (self.ok()) { self.shutdown() catch |err| { std.log.err("failed to shutdown context in deinit: {}\n", .{err}); }; } const fini_ret = rcl.rcl_context_fini(&self.rcl_context); if (fini_ret != rcl.RCL_RET_OK) { // Should not happen unless there's a bug in rcl std.log.err("failed to finalize rcl_context_t ({})\n", .{fini_ret}); } } pub fn shutdown(self: *Context) !void { const rcl_ret = rcl.rcl_shutdown(&self.rcl_context); if (rcl_ret != rcl.RCL_RET_OK) { return fromRclError(rcl_ret); } } pub fn ok(self: *Context) bool { return rcl.rcl_context_is_valid(&self.rcl_context); } }; test "check for memory leaks" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); const argv = [_][]const u8{}; var context_options = try ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try Context.init(&argv, context_options); // implicit shutdown expected context.deinit(); try std.testing.expect(!context.ok()); } test "init shutdown cycle" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); const argv = [_][]const u8{}; var context_options = try ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try Context.init(&argv, context_options); defer context.deinit(); try std.testing.expect(context.ok()); try context.shutdown(); try std.testing.expect(!context.ok()); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/rclzig.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub const Context = context.Context; pub const ContextOptions = context.ContextOptions; pub const Node = node.Node; pub const NodeOptions = node.NodeOptions; pub const Publisher = publisher.Publisher; pub const PublisherOptions = publisher.PublisherOptions; pub const RclAllocator = allocator.RclAllocator; pub const Subscription = subscription.Subscription; pub const SubscriptionOptions = subscription.SubscriptionOptions; pub const allocator = @import("allocator.zig"); pub const context = @import("context.zig"); pub const errors = @import("errors.zig"); pub const node = @import("node.zig"); pub const publisher = @import("publisher.zig"); pub const subscription = @import("subscription.zig"); test { _ = allocator; _ = context; _ = errors; _ = node; _ = publisher; _ = subscription; }
0
repos/rclzig/src
repos/rclzig/src/rclzig/errors.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const rcl = @import("rcl.zig").rcl; // Possible rcl error codes // Defined here: https://github.com/ros2/rcl/blob/master/rcl/include/rcl/types.h pub const RclzigError = RmwError || RclError || NodeError || PublisherError || SubscriptionError || ClientError || ServiceError || TimerError || WaitSetError || ArgumentError || EventError || LifecycleStateError; pub const RmwError = error{ Unspecified, Timeout, BadAlloc, ArgumentInvalid, Unsupported, }; pub const RclError = error{ AlreadyInit, NotInit, MismatchedRmwId, TopicNameInvalid, ServiceNameInvalid, UnknownSubstitution, AlreadyShutdown, }; pub const NodeError = error{ NodeInvalid, NodeNameInvalid, NodeNamespaceInvalid, NodeNameNonExistent, }; pub const PublisherError = error{ PublisherInvalid, }; pub const SubscriptionError = error{ SubscriptionInvalid, SubscriptionTakeFailed, }; pub const ClientError = error{ ClientInvalid, ClientTakeFailed, }; pub const ServiceError = error{ ServiceInvalid, ServiceTakeFailed, }; pub const TimerError = error{ TimerInvalid, TimerCanceled, }; pub const WaitSetError = error{ WaitSetInvalid, WaitSetEmpty, WaitSetFull, }; pub const ArgumentError = error{ RemapRuleInvalid, WrongLexeme, RosArgumentInvalid, ParamRuleInvalid, LogLevelRuleInvalid, }; pub const EventError = error{ EventInvalid, EventTakeFailed, }; pub const LifecycleStateError = error{ LifecycleStateRegistered, LifecycleStateNotRegistered, }; pub fn fromRclError(rcl_ret: i32) RclzigError { return switch (rcl_ret) { rcl.RCL_RET_TIMEOUT => RclzigError.Timeout, rcl.RCL_RET_BAD_ALLOC => RclzigError.BadAlloc, rcl.RCL_RET_INVALID_ARGUMENT => RclzigError.ArgumentInvalid, rcl.RCL_RET_UNSUPPORTED => RclzigError.Unsupported, rcl.RCL_RET_ALREADY_INIT => RclzigError.AlreadyInit, rcl.RCL_RET_NOT_INIT => RclzigError.NotInit, rcl.RCL_RET_MISMATCHED_RMW_ID => RclzigError.MismatchedRmwId, rcl.RCL_RET_TOPIC_NAME_INVALID => RclzigError.TopicNameInvalid, rcl.RCL_RET_SERVICE_NAME_INVALID => RclzigError.ServiceNameInvalid, rcl.RCL_RET_UNKNOWN_SUBSTITUTION => RclzigError.UnknownSubstitution, rcl.RCL_RET_ALREADY_SHUTDOWN => RclzigError.AlreadyShutdown, rcl.RCL_RET_NODE_INVALID => RclzigError.NodeInvalid, rcl.RCL_RET_NODE_INVALID_NAME => RclzigError.NodeNameInvalid, rcl.RCL_RET_NODE_INVALID_NAMESPACE => RclzigError.NodeNamespaceInvalid, rcl.RCL_RET_NODE_NAME_NON_EXISTENT => RclzigError.NodeNameNonExistent, rcl.RCL_RET_PUBLISHER_INVALID => RclzigError.PublisherInvalid, rcl.RCL_RET_SUBSCRIPTION_INVALID => RclzigError.SubscriptionInvalid, rcl.RCL_RET_SUBSCRIPTION_TAKE_FAILED => RclzigError.SubscriptionTakeFailed, rcl.RCL_RET_CLIENT_INVALID => RclzigError.ClientInvalid, rcl.RCL_RET_CLIENT_TAKE_FAILED => RclzigError.ClientTakeFailed, rcl.RCL_RET_SERVICE_INVALID => RclzigError.ServiceInvalid, rcl.RCL_RET_SERVICE_TAKE_FAILED => RclzigError.ServiceTakeFailed, rcl.RCL_RET_TIMER_INVALID => RclzigError.TimerInvalid, rcl.RCL_RET_TIMER_CANCELED => RclzigError.TimerCanceled, rcl.RCL_RET_WAIT_SET_INVALID => RclzigError.WaitSetInvalid, rcl.RCL_RET_WAIT_SET_EMPTY => RclzigError.WaitSetEmpty, rcl.RCL_RET_WAIT_SET_FULL => RclzigError.WaitSetFull, rcl.RCL_RET_INVALID_REMAP_RULE => RclzigError.RemapRuleInvalid, rcl.RCL_RET_WRONG_LEXEME => RclzigError.WrongLexeme, rcl.RCL_RET_INVALID_ROS_ARGS => RclzigError.RosArgumentInvalid, rcl.RCL_RET_INVALID_PARAM_RULE => RclzigError.ParamRuleInvalid, rcl.RCL_RET_INVALID_LOG_LEVEL_RULE => RclzigError.LogLevelRuleInvalid, rcl.RCL_RET_EVENT_INVALID => RclzigError.EventInvalid, rcl.RCL_RET_EVENT_TAKE_FAILED => RclzigError.EventTakeFailed, // rcl.RCL_RET_LIFECYCLE_STATE_REGISTERED => RclzigError.LifecycleStateRegistered, // rcl.RCL_RET_LIFECYCLE_STATE_NOT_REGISTERED => RclzigError.LifecycleStateNotRegistered, rcl.RCL_RET_ERROR => RclzigError.Unspecified, else => RclzigError.Unspecified, }; }
0
repos/rclzig/src
repos/rclzig/src/rclzig/node.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rcl.zig").rcl; const Context = @import("context.zig").Context; const ContextOptions = @import("context.zig").ContextOptions; const RclAllocator = @import("allocator.zig").RclAllocator; const fromRclError = @import("errors.zig").fromRclError; pub const NodeOptions = struct { rcl_options: rcl.rcl_node_options_t, pub fn init(allocator: *RclAllocator) NodeOptions { var node_options = NodeOptions{ .rcl_options = rcl.rcl_node_get_default_options(), }; node_options.rcl_options.allocator = allocator.c_allocator; return node_options; } pub fn deinit(self: *NodeOptions) void { const fini_ret = rcl.rcl_node_options_fini(&self.rcl_options); if (fini_ret != rcl.RCL_RET_OK) { std.log.err("failed to finalize rcl_node_options_t ({})\n", .{fini_ret}); } } }; pub const Node = struct { rcl_node: rcl.rcl_node_t, name: []const u8, namespace: []const u8, pub fn init(name: []const u8, namespace: []const u8, context: *Context, options: NodeOptions) !Node { var node = Node{ .rcl_node = rcl.rcl_get_zero_initialized_node(), .name = name, .namespace = namespace, }; var init_ret = rcl.rcl_node_init(&node.rcl_node, @ptrToInt(node.name.ptr), @ptrToInt(node.namespace.ptr), &context.rcl_context, &options.rcl_options); if (init_ret != rcl.RCL_RET_OK) { return fromRclError(init_ret); } return node; } pub fn deinit(self: *Node) void { const fini_ret = rcl.rcl_node_fini(&self.rcl_node); if (fini_ret != rcl.RCL_RET_OK) { std.log.err("failed to finalize rcl_node_t ({})\n", .{fini_ret}); } } }; test "check for memory leaks" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); // Initialize Context const argv = [_][]const u8{}; var context_options = try ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try Context.init(&argv, context_options); defer context.deinit(); // Initialize Node var node_options = NodeOptions.init(rcl_allocator); defer node_options.deinit(); var node_name: []const u8 = "bar"; var node_namespace: []const u8 = "foo"; var node = try Node.init(node_name, node_namespace, &context, node_options); defer node.deinit(); // Shutdown Context try context.shutdown(); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/allocator.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // const std = @import("std"); const rcl = @import("rcl.zig").rcl; pub const RclAllocator = packed struct { c_allocator: rcl.rcl_allocator_t, zig_allocator: *std.mem.Allocator, mem_map: *std.AutoHashMap(usize, usize), pub fn init(allocator: *std.mem.Allocator) !*RclAllocator { var rcl_allocator = try allocator.create(RclAllocator); rcl_allocator.* = RclAllocator{ .c_allocator = rcl.rcutils_get_zero_initialized_allocator(), .zig_allocator = allocator, .mem_map = blk: { var auto_hash_ptr = try allocator.create(std.AutoHashMap(usize, usize)); auto_hash_ptr.* = std.AutoHashMap(usize, usize).init(allocator); break :blk auto_hash_ptr; }, }; rcl_allocator.c_allocator.state = @ptrCast(*c_void, rcl_allocator); rcl_allocator.c_allocator.allocate = rclAllocate; rcl_allocator.c_allocator.deallocate = rclDeallocate; rcl_allocator.c_allocator.reallocate = rclReallocate; rcl_allocator.c_allocator.zero_allocate = rclZeroAllocate; return rcl_allocator; } pub fn deinit(self: *RclAllocator) void { self.mem_map.deinit(); self.zig_allocator.destroy(self.mem_map); self.zig_allocator.destroy(self); } }; fn rclAllocate(size: usize, state: ?*c_void) callconv(.C) ?*c_void { var rcl_allocator = @ptrCast(*RclAllocator, state); // Or without a packed struct: // var rcl_allocator = @intToPtr(*RclAllocator, @ptrToInt(state)); var result = rcl_allocator.zig_allocator.alloc(u8, size) catch |err| { std.log.err("error allocating memory: {e}\n", .{err}); return null; }; rcl_allocator.mem_map.put(@ptrToInt(result.ptr), result.len) catch |err| { std.log.err("error updating memory map: {e}\n", .{err}); rcl_allocator.zig_allocator.free(result); return null; }; // std.debug.print("allocated {} bytes at {}\n", .{ result.len, @ptrToInt(result.ptr) }); return result.ptr; } fn rclDeallocate(opt_c_pointer: ?*c_void, state: ?*c_void) callconv(.C) void { var rcl_allocator = @ptrCast(*RclAllocator, state); if (opt_c_pointer) |c_pointer| { var zig_pointer = @ptrCast([*]u8, c_pointer); // std.debug.print("deallocating at {}\n", .{@ptrToInt(c_pointer)}); const opt_entry = rcl_allocator.mem_map.fetchRemove(@ptrToInt(c_pointer)); if (opt_entry) |entry| { const size = entry.value; rcl_allocator.zig_allocator.free(zig_pointer[0..size]); } else { // unreachable, unless there's a bug in rcl/rmw // std.log.err("tried to deallocate at unknown address {}\n", .{@ptrToInt(c_pointer)}); unreachable; } } } fn rclReallocate(opt_c_pointer: ?*c_void, size: usize, state: ?*c_void) callconv(.C) ?*c_void { var rcl_allocator = @ptrCast(*RclAllocator, state); if (opt_c_pointer) |c_pointer| { var zig_pointer = @ptrCast([*]u8, c_pointer); const opt_old_size = rcl_allocator.mem_map.get(@ptrToInt(c_pointer)); if (opt_old_size) |old_size| { var result = rcl_allocator.zig_allocator.realloc(zig_pointer[0..old_size], size) catch |err| { std.log.err("error during realloc: {e}\n", .{err}); return null; }; rcl_allocator.mem_map.put(@ptrToInt(result.ptr), result.len) catch |err| { std.log.err("error updating memory map: {e}\n", .{err}); rcl_allocator.zig_allocator.free(result); return null; }; return result.ptr; } else { // unreachable, unless there's a bug in rcl // std.log.err("tried to reallocate at unknown address {}\n", .{@ptrToInt(c_pointer)}); unreachable; } } return null; } fn rclZeroAllocate(numOfElements: usize, sizeOfElement: usize, state: ?*c_void) callconv(.C) ?*c_void { const numBytes: usize = numOfElements * sizeOfElement; var opt_result = rclAllocate(numBytes, state); if (opt_result) |result| { var ptr = @ptrCast([*]u8, result); const slice: []u8 = ptr[0..numBytes]; std.mem.set(u8, slice, 0); return slice.ptr; } return null; } test "check for memory leaks" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/publisher.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rcl.zig").rcl; const Node = @import("node.zig").Node; const RclAllocator = @import("allocator.zig").RclAllocator; const fromRclError = @import("errors.zig").fromRclError; pub const PublisherOptions = struct { rcl_options: rcl.rcl_publisher_options_t, rcl_allocator: *RclAllocator, pub fn init(allocator: *RclAllocator) PublisherOptions { var publisher_options = PublisherOptions{ .rcl_options = rcl.rcl_publisher_get_default_options(), .rcl_allocator = allocator, }; publisher_options.rcl_options.allocator = allocator.c_allocator; return publisher_options; } }; pub fn Publisher(comptime MsgType: type) type { return struct { rcl_publisher: rcl.rcl_publisher_t, type_support: MsgType, const Self = @This(); pub fn init(node: Node, topic_name: []const u8, options: PublisherOptions) !Self { var publisher = Self{ .rcl_publisher = rcl.rcl_get_zero_initialized_publisher(), .type_support = try MsgType.init(options.rcl_allocator.zig_allocator), }; const init_ret = rcl.rcl_publisher_init(&publisher.rcl_publisher, &node.rcl_node, @ptrToInt(publisher.type_support.rcl_type_support), @ptrToInt(topic_name.ptr), &options.rcl_options); if (init_ret != rcl.RCL_RET_OK) { return fromRclError(init_ret); } return publisher; } pub fn deinit(self: *Self, node: *Node) void { self.type_support.deinit(); const fini_ret = rcl.rcl_publisher_fini(&self.rcl_publisher, &node.rcl_node); if (fini_ret != rcl.RCL_RET_OK) { std.log.err("failed to finalize rcl_publisher_t ({})\n", .{fini_ret}); } } pub fn publish(self: *Self, message: MsgType) void { const ret = rcl.rcl_publish(&self.rcl_publisher, message.rcl_message, 0); if (ret != rcl.RCL_RET_OK) { std.log.err("failed to publish message ({})\n", .{ret}); } } }; } // Imports for testing const Context = @import("context.zig").Context; const ContextOptions = @import("context.zig").ContextOptions; const NodeOptions = @import("node.zig").NodeOptions; const std_msgs = @import("std_msgs"); test "check for memory leaks" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); // Initialize Context const argv = [_][]const u8{}; var context_options = try ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try Context.init(&argv, context_options); defer context.deinit(); // Initialize Node var node_options = NodeOptions.init(rcl_allocator); defer node_options.deinit(); var node_name: []const u8 = "bar"; var node_namespace: []const u8 = "foo"; var node = try Node.init(node_name, node_namespace, &context, node_options); defer node.deinit(); // Initialize Publisher var publisher_options = PublisherOptions.init(rcl_allocator); var publisher = try Publisher(std_msgs.msg.String).init(node, "chatter", publisher_options); defer publisher.deinit(&node); // Shutdown Context try context.shutdown(); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/subscription.zig
// Copyright 2022 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rcl.zig").rcl; const Node = @import("node.zig").Node; const RclAllocator = @import("allocator.zig").RclAllocator; const fromRclError = @import("errors.zig").fromRclError; pub const MessageInfo = struct { rmw_message_info: rcl.rmw_message_info_t, pub fn init() MessageInfo { return MessageInfo{ .rmw_message_info = rcl.rmw_get_zero_initialized_message_info(), }; } }; pub const SubscriptionOptions = struct { rcl_options: rcl.rcl_subscription_options_t, rcl_allocator: *RclAllocator, pub fn init(allocator: *RclAllocator) SubscriptionOptions { var subscription_options = SubscriptionOptions{ .rcl_options = rcl.rcl_subscription_get_default_options(), .rcl_allocator = allocator, }; subscription_options.rcl_options.allocator = allocator.c_allocator; return subscription_options; } }; pub fn Subscription(comptime MsgType: type) type { return struct { rcl_subscription: rcl.rcl_subscription_t, type_support: MsgType, options: SubscriptionOptions, const Self = @This(); pub fn init(node: Node, topic_name: []const u8, options: SubscriptionOptions) !Self { var subscription = Self{ .rcl_subscription = rcl.rcl_get_zero_initialized_subscription(), .type_support = try MsgType.init(options.rcl_allocator.zig_allocator), .options = options, }; const init_ret = rcl.rcl_subscription_init(&subscription.rcl_subscription, &node.rcl_node, @ptrToInt(subscription.type_support.rcl_type_support), @ptrToInt(topic_name.ptr), &options.rcl_options); if (init_ret != rcl.RCL_RET_OK) { return fromRclError(init_ret); } return subscription; } pub fn deinit(self: *Self, node: *Node) void { self.type_support.deinit(); const fini_ret = rcl.rcl_subscription_fini(&self.rcl_subscription, &node.rcl_node); if (fini_ret != rcl.RCL_RET_OK) { std.log.err("failed to finalize rcl_subscription_t ({})\n", .{fini_ret}); } } pub fn take(self: *Self, message_info: *MessageInfo) !?MsgType { var message: MsgType = try MsgType.init(self.options.rcl_allocator.zig_allocator); const ret = rcl.rcl_take(&self.rcl_subscription, message.rcl_message, &message_info.rmw_message_info, 0); if (ret == rcl.RCL_RET_SUBSCRIPTION_TAKE_FAILED) { message.deinit(); return null; } if (ret != rcl.RCL_RET_OK) { message.deinit(); return fromRclError(ret); } return message; } }; } // Imports for testing const Context = @import("context.zig").Context; const ContextOptions = @import("context.zig").ContextOptions; const NodeOptions = @import("node.zig").NodeOptions; const std_msgs = @import("std_msgs"); test "check for memory leaks" { var rcl_allocator = try RclAllocator.init(std.testing.allocator); defer rcl_allocator.deinit(); // Initialize Context const argv = [_][]const u8{}; var context_options = try ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try Context.init(&argv, context_options); defer context.deinit(); // Initialize Node var node_options = NodeOptions.init(rcl_allocator); defer node_options.deinit(); var node_name: []const u8 = "bar"; var node_namespace: []const u8 = "foo"; var node = try Node.init(node_name, node_namespace, &context, node_options); defer node.deinit(); // Initialize Subscription var subscription_options = SubscriptionOptions.init(rcl_allocator); var subscription = try Subscription(std_msgs.msg.String).init(node, "chatter", subscription_options); defer subscription.deinit(&node); // Take var msg_info = MessageInfo.init(); var msg_opt: ?std_msgs.msg.String = try subscription.take(&msg_info); try std.testing.expectEqual(msg_opt, null); // Shutdown Context try context.shutdown(); }
0
repos/rclzig/src
repos/rclzig/src/rclzig/rcl.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub const rcl = @cImport({ @cInclude("rcl/rcl.h"); @cInclude("rcutils/allocator.h"); });
0
repos/rclzig/src
repos/rclzig/src/std_msgs/msg.zig
pub const String = @import("string.zig").String; const string = @import("string.zig"); test { _ = string; }
0
repos/rclzig/src
repos/rclzig/src/std_msgs/std_msgs.zig
pub const msg = @import("msg.zig"); test { _ = msg; }
0
repos/rclzig/src
repos/rclzig/src/std_msgs/string.zig
const std = @import("std"); pub const c = @cImport({ @cInclude("std_msgs/msg/string.h"); @cInclude("rosidl_runtime_c/string_functions.h"); }); pub const String = struct { rcl_type_support: *const c.rosidl_message_type_support_t, rcl_message: *c.std_msgs__msg__String, pub fn init(allocator: *std.mem.Allocator) !String { // TODO(jacobperron): Use allocator to initialize message when it is available // https://github.com/ros2/rosidl/issues/306 _ = allocator; var rcl_message = c.std_msgs__msg__String__create(); var message: String = .{ // We can't call ROSIDL_GET_MSG_TYPE_SUPPORT because zig cannot translate the macro .rcl_type_support = c.rosidl_typesupport_c__get_message_type_support_handle__std_msgs__msg__String(), .rcl_message = rcl_message, }; return message; } pub fn deinit(self: *String) void { c.std_msgs__msg__String__destroy(self.rcl_message); } pub fn setData(self: *String, data: []const u8) !void { const success = c.rosidl_runtime_c__String__assign(&self.rcl_message.data, @ptrToInt(data.ptr)); if (!success) { // TODO(jacobperron): return error } } pub fn getData(self: String) []const u8 { return self.rcl_message.data.data[0..self.rcl_message.data.size]; } }; test "init/deinit" { var my_msg: String = try String.init(std.testing.allocator); defer my_msg.deinit(); _ = my_msg; } test "set/get" { var my_msg: String = try String.init(std.testing.allocator); defer my_msg.deinit(); try my_msg.setData("foobar"); var data: []const u8 = my_msg.getData(); try std.testing.expectEqualStrings(data, "foobar"); try my_msg.setData("Hello World: 42"); data = my_msg.getData(); try std.testing.expectEqualStrings(data, "Hello World: 42"); try my_msg.setData(""); data = my_msg.getData(); try std.testing.expectEqualStrings(data, ""); }
0
repos/rclzig/src
repos/rclzig/src/examples/talker.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rclzig"); const std_msgs = @import("std_msgs"); pub fn main() anyerror!void { std.log.info("Start rclzig talker\n", .{}); // Initialize zig allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Initialize rcl allocator (using zig allocator) var rcl_allocator = try rcl.RclAllocator.init(allocator); defer rcl_allocator.deinit(); const argv = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, argv); // Initialize Context var context_options = try rcl.ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try rcl.Context.init(argv, context_options); defer context.deinit(); // Initialize Node var node_options = rcl.NodeOptions.init(rcl_allocator); defer node_options.deinit(); var node = try rcl.Node.init("talker", "", &context, node_options); defer node.deinit(); // Create publisher var publisher_options = rcl.PublisherOptions.init(rcl_allocator); var publisher = try rcl.Publisher(std_msgs.msg.String).init(node, "chatter", publisher_options); defer publisher.deinit(&node); // Create a message to publish var message = try std_msgs.msg.String.init(rcl_allocator.zig_allocator); defer message.deinit(); try message.setData("Hello world"); // Start publishing var timer = try std.time.Timer.start(); const publish_period: u64 = 1e9; while (true) { const time_since_publish: u64 = timer.read(); if (time_since_publish >= publish_period) { std.log.info("Publishing message\n", .{}); publisher.publish(message); timer.reset(); continue; } std.time.sleep(publish_period - time_since_publish); } // Shutdown Context try context.shutdown(); }
0
repos/rclzig/src
repos/rclzig/src/examples/listener.zig
// Copyright 2021 Jacob Perron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const std = @import("std"); const rcl = @import("rclzig"); const std_msgs = @import("std_msgs"); pub fn main() anyerror!void { std.log.info("Start rclzig listener", .{}); // Initialize zig allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Initialize rcl allocator (using zig allocator) var rcl_allocator = try rcl.RclAllocator.init(allocator); defer rcl_allocator.deinit(); const argv = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, argv); // Initialize Context var context_options = try rcl.ContextOptions.init(rcl_allocator); defer context_options.deinit(); var context = try rcl.Context.init(argv, context_options); defer context.deinit(); // Initialize Node var node_options = rcl.NodeOptions.init(rcl_allocator); defer node_options.deinit(); var node = try rcl.Node.init("listener", "", &context, node_options); defer node.deinit(); // Create subscription var subscription_options = rcl.SubscriptionOptions.init(rcl_allocator); var subscription = try rcl.Subscription(std_msgs.msg.String).init(node, "chatter", subscription_options); defer subscription.deinit(&node); // Spin on node // TODO // Temporarily poll for messages const poll_period: u64 = 1e9; var msg_info = rcl.subscription.MessageInfo.init(); while (true) { var msg_opt: ?std_msgs.msg.String = try subscription.take(&msg_info); if (msg_opt) |*msg| { defer msg.deinit(); const data = msg.getData(); std.log.info("I heard: {s} \n", .{data}); } std.time.sleep(poll_period); } // Shutdown Context try context.shutdown(); }
0
repos
repos/ryu/run_benchmark.bat
bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=1 > win-fixed-1.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=10 > win-fixed-10.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=100 > win-fixed-100.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=1000 > win-fixed-1000.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=1 > win-exp-1.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=10 > win-exp-10.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=100 > win-exp-100.csv bazel run -c opt //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=1000 > win-exp-1000.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=1 > mingw-fixed-1.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=10 > mingw-fixed-10.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=100 > mingw-fixed-100.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -64 -samples=1000 -v -precision=1000 > mingw-fixed-1000.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=1 > mingw-exp-1.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=10 > mingw-exp-10.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=100 > mingw-exp-100.csv /c/Users/Ulf\ Adams/bin/bazel.exe --host_jvm_args="-Dbazel.windows_unix_root=C:/msys64/" run -c opt --compiler=msys-gcc //ryu/benchmark:benchmark_fixed_cc -- -exp -samples=1000 -v -precision=1000 > mingw-exp-1000.csv
0
repos
repos/ryu/run_benchmark_linux.sh
#!/bin/bash for i in 1 10 100 1000; do echo $i CC=clang-6.0 bazel run -c opt //ryu/benchmark:benchmark_fixed -- -samples=1000 -v -precision=$i > glibc-fixed-$i.csv CC=clang-6.0 bazel run -c opt //ryu/benchmark:benchmark_fixed -- -samples=1000 -v -precision=$i -exp > glibc-exp-$i.csv done #for i in 1 10 100 1000; do # echo $i # CC=musl-gcc bazel run -c opt //ryu/benchmark:benchmark_fixed -- -samples=1000 -v -precision=$i > musl-fixed-$i.csv # CC=musl-gcc bazel run -c opt //ryu/benchmark:benchmark_fixed -- -samples=1000 -v -precision=$i -exp > musl-exp-$i.csv #done
0
repos
repos/ryu/CMakeLists.txt
cmake_minimum_required(VERSION 3.4) project(ryu VERSION 2.0 LANGUAGES C) include(GNUInstallDirs) # ryu library add_library(ryu ryu/f2s.c ryu/f2s_full_table.h ryu/f2s_intrinsics.h ryu/d2s.c ryu/d2fixed.c ryu/d2fixed_full_table.h ryu/d2s_full_table.h ryu/d2s_small_table.h ryu/d2s_intrinsics.h ryu/digit_table.h ryu/common.h ryu/ryu.h) # This directory is the include root because the headers are in ryu/ and are included as "ryu/*.h" target_include_directories(ryu PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>) # add alias so the project can be used with add_subdirectory add_library(ryu::ryu ALIAS ryu) # Specify what to install if using CMake to install ryu. install(TARGETS ryu LIBRARY) install(FILES ryu/ryu.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ryu) # generic_128 # Only builds on GCC/Clang/Intel due to __uint128_t. No MSVC. if ("${CMAKE_C_COMPILER_ID}" MATCHES "Clang" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "Intel") add_library(generic_128 ryu/generic_128.c ryu/generic_128.h ryu/ryu_generic_128.h) target_include_directories(generic_128 PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>) add_library(ryu::generic_128 ALIAS generic_128) install(TARGETS generic_128 LIBRARY) install(FILES ryu/ryu_generic_128.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ryu) set(RYU_GENERIC_128_AVAILABLE ON CACHE BOOL "generic_128 available." FORCE) else() set(RYU_GENERIC_128_AVAILABLE OFF CACHE BOOL "generic_128 not available on this platform." FORCE) endif()
0
repos
repos/ryu/README.md
# Ryu & Ryu Printf [![Build Status](https://travis-ci.org/ulfjack/ryu.svg?branch=master)](https://travis-ci.org/ulfjack/ryu) This project contains routines to convert IEEE-754 floating-point numbers to decimal strings using shortest, fixed `%f`, and scientific `%e` formatting. The primary implementation is in C, and there is a port of the shortest conversion to Java. All algorithms have been published in peer-reviewed publications. At the time of this writing, these are the fastest known float-to-string conversion algorithms. The fixed, and scientific conversion routines are several times faster than the usual implementations of sprintf (we compared against glibc, Apple's libc, MSVC, and others). Generating scientific and fixed output format for 16 and 32 bit IEEE floating point numbers can be implemented by converting to 64 bit, and then using the 64 bit routines. Note that there is no 128 bit implementation at this time. When converting to shortest, DO NOT CAST; shortest conversion is based on the precision of the source type, and casting to a different type will not return the expected output. There are highly optimized 32 and 64 bit implementations as well as a generic 128 bit implementation that can handle any IEEE format up to 128 bits. These are the supported conversion modes for the C implementation: | IEEE Type | Supported Output Formats | | -------------------- | -------------------------------- | | 16 Bit (half) | Shortest (via ryu_generic_128.h) | | 32 Bit (float) | Shortest | | 64 Bit (double) | Shortest, Scientific, Fixed | | 80 Bit (long double) | Shortest (via ryu_generic_128.h) | | 128 Bit (__float128) | Shortest (via ryu_generic_128.h) | The code is continuously tested on Ubuntu 18.04, MacOS High Sierra, and Windows Server version 1803. All code outside of third_party/ is copyrighted by Ulf Adams and contributors, and may be used freely in accordance with the Apache 2.0 license. Alternatively, the files in the ryu/ directory may be used freely in accordance with the Boost 1.0 license. All contributions are required to maintain these licenses. ## Ryu Ryu generates the shortest decimal representation of a floating point number that maintains round-trip safety. That is, a correct parser can recover the exact original number. For example, consider the binary 32-bit floating point number `00111110100110011001100110011010`. The stored value is exactly `0.300000011920928955078125`. However, this floating point number is also the closest number to the decimal number `0.3`, so that is what Ryu outputs. This problem of generating the shortest possible representation was originally posed by White and Steele [[1]], for which they described an algorithm called "Dragon". It was subsequently improved upon with algorithms that also had dragon-themed names. I followed in the same vein using the japanese word for dragon, Ryu. In general, all these algorithms should produce identical output given identical input, and this is checked when running the benchmark program. The C implementation of Ryu is in the ryu/ directory. The Java implementations are RyuFloat and RyuDouble under src/main/java/. Both cover 32 and 64-bit floating point numbers. In addition, there is an experimental C implementation that can handle inputs of any size up to 128-bit, albeit with lower performance than the highly optimized 32-bit and 64-bit implementations. Furthermore, there is an experimental low-level C API that returns the decimal floating-point representation as a struct, allowing clients to implement their own formatting. These are still subject to change. *Note*: The Java implementation differs from the output of `Double.toString` [[2]] in some cases: sometimes the output is shorter (which is arguably more accurate) and sometimes the output may differ in the precise digits output (e.g., see https://github.com/ulfjack/ryu/issues/83). *Note*: While the Java specification requires outputting at least 2 digits, other specifications, such as for JavaScript, always require the shortest output. We may change the Java implementation in the future to support both. My PLDI'18 paper includes a complete correctness proof of the algorithm: https://dl.acm.org/citation.cfm?doid=3296979.3192369 Other implementations of Ryu: | Language | Author | Link | |------------------|--------------------|-----------------------------------------------| | Scala | Andriy Plokhotnyuk | [https://github.com/plokhotnyuk/jsoniter-scala][3] | | Rust | David Tolnay | https://github.com/dtolnay/ryu | | Julia | Jacob Quinn | https://github.com/JuliaLang/julia/tree/master/base/ryu | | Factor | Alexander Iljin | https://github.com/AlexIljin/ryu | | Go | Caleb Spare | https://github.com/cespare/ryu | | C# | Dogwei | https://github.com/Dogwei/RyuCsharp | | C# | Shad Storhaug | https://github.com/NightOwl888/J2N | | D | Ilya Yaroshenko | [https://github.com/libmir/mir-algorithm][5] | | Scala | Denys Shabalin | [https://github.com/scala-native/scala-native][4] | | Erlang/BEAM | Thomas Depierre | https://github.com/erlang/otp/tree/master/erts/emulator/ryu | | Zig | Marc Tiehuis | https://github.com/tiehuis/zig-ryu | | Haskell | [Lawrence Wu](https://github.com/la-wu) | [https://github.com/haskell/bytestring][6] | [1]: https://dl.acm.org/citation.cfm?id=93559 [2]: https://docs.oracle.com/javase/10/docs/api/java/lang/Double.html#toString(double) [3]: https://github.com/plokhotnyuk/jsoniter-scala/blob/6e6bb9d7bed6de341ce0b781b403eb671d008468/jsoniter-scala-core/jvm/src/main/scala/com/github/plokhotnyuk/jsoniter_scala/core/JsonWriter.scala#L1777-L2262 [4]: https://github.com/scala-native/scala-native/tree/master/nativelib/src/main/scala/scala/scalanative/runtime/ieee754tostring/ryu [5]: https://github.com/libmir/mir-algorithm/tree/master/source/mir/bignum/internal/ryu [6]: https://github.com/haskell/bytestring/pull/365 ## Ryu Printf Since Ryu generates the shortest decimal representation, it is not immediately suitable for use in languages that have printf-like facilities. In most implementations, printf provides three floating-point specific formatters, `%f`, `%e`, and `%g`: - The `%f` format prints the full decimal part of the given floating point number, and then appends as many digits of the fractional part as specified using the precision parameter. - The `%e` format prints the decimal number in scientific notation with as many digits after the initial digit as specified using the precision parameter. - The `%g` format prints either `%f` or `%e` format, whichever is shorter. Ryu Printf implements %f and %e formatting in a way that should be drop-in compatible with most implementations of printf, although it currently does not implement any formatting flags other than precision. The benchmark program verifies that the output matches exactly, and outputs a warning if not. Any unexpected output from the benchmark indicates a difference in output. *Note* that old versions of MSVC ship with a printf implementation that has a confirmed bug: it does not always round the last digit correctly. *Note* that msys cuts off the output after ~17 digits, and therefore generally differs from Ryu Printf output for precision values larger than 17. *Note* that the output for NaN values can differ between implementations; we use ifdefs in an attempt to match platform output. According to our benchmarks, Ryu Printf compares favorably with the following implementations of printf for precision parameters 1, 10, 100, and 1000: | OS | Libc | Ryu Printf is faster by | |----------------------|-----------------------------|-------------------------| | Ubuntu 18.04 | libc6 2.27-3ubuntu1 | 15x | | Ubuntu 18.04 | musl 1.1.19-1 | 4x | | Windows 10 Home 1803 | MSVC 19.14.26429.4 | 9x | | Windows 10 Home 1803 | msys-runtime-devel 2.10.0-2 | between 8x and 20x | | macOS Mojave 10.14 | Apple Libc | 24x | In addition, Ryu Printf has a more predictable performance profile. In theory, an implementation that performs particularly badly for some subset of numbers could be exploited as a denial-of-service attack vector. My OOPSLA'2019 paper provides a correctness proof: https://dl.acm.org/citation.cfm?doid=3366395.3360595 ## Building, Testing, Running We use the Bazel build system (https://bazel.build) 0.14 or later, although we recommend using the latest release. You also need to install Jdk 8 (or later) to build and run the Java code, and/or a C/C++ compiler (gcc or clang on Ubuntu, XCode on MacOS, or MSVC on Windows) to build the C/C++ code. To build Ryu, run ``` $ bazel build //ryu ``` To build Ryu Printf, run ``` $ bazel build //ryu:ryu_printf ``` ### Big-Endian Architectures The C implementations should work on big-endian architectures provided that the floating point type and the corresponding integer type use the same endianness. There are no concerns around endianness for the Java implementation. ### Building with a Custom Compiler You can select a custom C++ compiler by setting the CC environment variable, e.g., use these steps to build with clang-4.0 on Ubuntu: ``` $ export CC=clang-4.0 $ bazel build //ryu ``` Building Ryu Printf against musl and msys requires installing the corresponding packages. We only tested against the musl Debian package that installs a gcc wrapper and is enabled by setting `CC`. However, building against msys requires manually adjusting Bazel's compiler configuration files. ### Tests You can run both C and Java tests with ``` $ bazel test //ryu/... //src/... ``` ## Ryu: Additional Notes ### Jaffer The code given by Jaffer in the original paper does not come with a license declaration. Instead, we're using code found on GitHub [3], which contains a license declaration by Jaffer. Compared to the original code, this implementation no longer outputs incorrect values for negative numbers. We provide a binary to find differences between Ryu and the Jaffer / Jdk implementations: ``` $ bazel run //src/main/java/info/adams/ryu/analysis:FindDifferences -- ``` Add the `-mode=csv` option to get all the discovered differences as a CSV. Use `-mode=latex` instead to get a latex snippet of the first 20. Use `-mode=summary` to only print the number of discovered differences (this is the default mode). [3]: https://github.com/coconut2015/cookjson/blob/master/cookjson-core/src/main/java/org/yuanheng/cookjson/DoubleUtils.java ### Computing Required Lookup Table Sizes You can compute the required lookup table sizes with: ``` $ bazel run //src/main/java/info/adams/ryu/analysis:ComputeTableSizes -- ``` Add `-v` to get slightly more verbose output. ### Computing Required Bit Sizes You can compute the required bit sizes with: ``` $ bazel run //src/main/java/info/adams/ryu/analysis:ComputeRequiredBitSizes -- ``` Add the `-128` and `-256` flags to also cover 128- and 256-bit numbers. This could take a while - 128-bit takes ~20 seconds on my machine while 256-bit takes a few hours. Add `-v` to get very verbose output. ### Java: Comparing All Possible 32-bit Values Exhaustively You can check the slow vs. the fast implementation for all 32-bit floating point numbers using: ``` $ bazel run //src/main/java/info/adams/ryu/analysis:ExhaustiveFloatComparison ``` This takes ~60 hours to run to completion on an Intel(R) Core(TM) i7-4770K with 3.50GHz. ### Java: Comparing All Possible 64-bit Values Exhaustively You can check the slow vs. the fast implementation for all 64-bit floating point numbers using: ``` $ bazel run //src/main/java/info/adams/ryu/analysis:ExtensiveDoubleComparison ``` This takes approximately forever, so you will need to interrupt the program. ## Benchmarks ### Ryu We provide both C and Java benchmark programs. Enable optimization by adding "-c opt" on the command line: ``` $ bazel run -c opt //ryu/benchmark:ryu_benchmark -- Average & Stddev Ryu Average & Stddev Grisu3 32: 22.515 1.578 90.981 41.455 64: 27.545 1.677 98.981 80.797 ``` For the Java benchmark, run: ``` $ bazel run //src/main/java/info/adams/ryu/benchmark -- Average & Stddev Ryu Average & Stddev Jdk Average & Stddev Jaffer 32: 56.680 9.127 254.903 170.099 64: 89.751 13.442 1085.596 302.371 1089.535 309.245 ``` Additional parameters can be passed to the benchmark after the `--` parameter: ``` -32 only run the 32-bit benchmark -64 only run the 64-bit benchmark -samples=n run n pseudo-randomly selected numbers -iterations=n run each number n times -ryu run Ryu only, no comparison -v generate verbose output in CSV format ``` If you have gnuplot installed, you can generate plots from the benchmark data with: ``` $ bazel build -c opt --jobs=1 //scripts:shortest-{c,java}-{float,double}.pdf ``` The resulting files are `bazel-genfiles/scripts/shortest-{c,java}-{float,double}.pdf`. ### Ryu Printf We provide a C++ benchmark program that runs against the implementation of `snprintf` bundled with the selected C++ compiler. You need to enable optimization using "-c opt" on the command line: ``` $ bazel run -c opt //ryu/benchmark:ryu_printf_benchmark -- Average & Stddev Ryu Average & Stddev snprintf %f: 116.359 130.992 3983.251 5331.505 %e: 40.853 10.872 210.648 36.779 ``` Additional parameters can be passed to the benchmark after the `--` parameter: ``` -f only run the %f benchmark -e only run the %e benchmark -precision=n run with precision n (default is 6) -samples=n run n pseudo-randomly selected numbers -iterations=n run each number n times -ryu run Ryu Printf only, no comparison -v generate verbose output in CSV format ``` See above for selecting a different compiler. Note that msys C++ compilation does not work out of the box. We also provide a simplified C benchmark for platforms that do not support C++ compilation, but *note* that pure C compilation is not natively supported by Bazel: ``` $ bazel run -c opt //ryu/benchmark:ryu_printf_benchmark_c -- ``` If you have gnuplot installed, you can generate plots from the benchmark data with: ``` $ bazel build -c opt --jobs=1 //scripts:{f,e}-c-double-{1,10,100,1000}.pdf ``` The resulting files are `bazel-genfiles/scripts/{f,e}-c-double-{1,10,100,1000}.pdf`.
0
repos/ryu/third_party
repos/ryu/third_party/double-conversion/double-conversionBuildTreeSettings.cmake.in
set(double-conversion_INCLUDE_DIRS "@PROJECT_SOURCE_DIR@/src")
0
repos/ryu/third_party
repos/ryu/third_party/double-conversion/double-conversionConfigVersion.cmake.in
set(PACKAGE_VERSION "@double-conversion_VERSION@") # Check whether the requested PACKAGE_FIND_VERSION is compatible if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") set(PACKAGE_VERSION_EXACT TRUE) endif() endif()
0
repos/ryu/third_party
repos/ryu/third_party/double-conversion/double-conversionConfig.cmake.in
# - Config file for the double-conversion package # It defines the following variables # double-conversion_INCLUDE_DIRS # double-conversion_LIBRARIES get_filename_component(double-conversion_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) if(EXISTS "${double-conversion_CMAKE_DIR}/CMakeCache.txt") include("${double-conversion_CMAKE_DIR}/double-conversionBuildTreeSettings.cmake") else() set(double-conversion_INCLUDE_DIRS "@CMAKE_INSTALL_FULL_INCLUDEDIR@/double-conversion") endif() include("@CMAKE_INSTALL_FULL_LIBDIR@/cmake/double-conversion/double-conversionLibraryDepends.cmake") set(double-conversion_LIBRARIES double-conversion)
0
repos/ryu/third_party
repos/ryu/third_party/double-conversion/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12) project(double-conversion) include(GNUInstallDirs) # pick a version # set(double-conversion_VERSION 2.0.1) set(double-conversion_SOVERSION_MAJOR 1) set(double-conversion_SOVERSION_MINOR 0) set(double-conversion_SOVERSION_PATCH 0) set(double-conversion_SOVERSION ${double-conversion_SOVERSION_MAJOR}.${double-conversion_SOVERSION_MINOR}.${double-conversion_SOVERSION_PATCH}) # set suffix for CMake files used for packaging if(WIN32 AND NOT CYGWIN) set(INSTALL_CMAKE_DIR CMake) else() set(INSTALL_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/double-conversion) endif() # Add src subdirectory add_subdirectory(double-conversion) # # set up testing if requested option(BUILD_TESTING "Build test programs" OFF) if(BUILD_TESTING) enable_testing() include(CTest) add_subdirectory(test) endif() # # mention the library target as export library export(TARGETS double-conversion FILE "${PROJECT_BINARY_DIR}/double-conversionLibraryDepends.cmake") # # set this build as an importable package export(PACKAGE double-conversion) # # make a cmake file -- in this case, all that needs defining # is double-conversion_INCLUDE_DIRS configure_file(double-conversionBuildTreeSettings.cmake.in "${PROJECT_BINARY_DIR}/double-conversionBuildTreeSettings.cmake" @ONLY) # # sets up config to be used by CMake find_package configure_file(double-conversionConfig.cmake.in "${PROJECT_BINARY_DIR}/double-conversionConfig.cmake" @ONLY) # # Export version # checked by find_package configure_file(double-conversionConfigVersion.cmake.in "${PROJECT_BINARY_DIR}/double-conversionConfigVersion.cmake" @ONLY) # # install config files for find_package install(FILES "${PROJECT_BINARY_DIR}/double-conversionConfig.cmake" "${PROJECT_BINARY_DIR}/double-conversionConfigVersion.cmake" DESTINATION "${INSTALL_CMAKE_DIR}" COMPONENT dev) # # generates install cmake files to find libraries in installation. install(EXPORT double-conversionLibraryDepends DESTINATION "${INSTALL_CMAKE_DIR}" COMPONENT dev)
0
repos/ryu/third_party
repos/ryu/third_party/double-conversion/README.md
https://github.com/google/double-conversion This project (double-conversion) provides binary-decimal and decimal-binary routines for IEEE doubles. The library consists of efficient conversion routines that have been extracted from the V8 JavaScript engine. The code has been refactored and improved so that it can be used more easily in other projects. There is extensive documentation in `double-conversion/double-conversion.h`. Other examples can be found in `test/cctest/test-conversions.cc`. Building ======== This library can be built with [scons][0] or [cmake][1]. The checked-in Makefile simply forwards to scons, and provides a shortcut to run all tests: make make test Scons ----- The easiest way to install this library is to use `scons`. It builds the static and shared library, and is set up to install those at the correct locations: scons install Use the `DESTDIR` option to change the target directory: scons DESTDIR=alternative_directory install Cmake ----- To use cmake run `cmake .` in the root directory. This overwrites the existing Makefile. Use `-DBUILD_SHARED_LIBS=ON` to enable the compilation of shared libraries. Note that this disables static libraries. There is currently no way to build both libraries at the same time with cmake. Use `-DBUILD_TESTING=ON` to build the test executable. cmake . -DBUILD_TESTING=ON make test/cctest/cctest --list | tr -d '<' | xargs test/cctest/cctest [0]: http://www.scons.org/ [1]: https://cmake.org/
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/bignum-dtoa.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_BIGNUM_DTOA_H_ #define DOUBLE_CONVERSION_BIGNUM_DTOA_H_ #include "utils.h" namespace double_conversion { enum BignumDtoaMode { // Return the shortest correct representation. // For example the output of 0.299999999999999988897 is (the less accurate but // correct) 0.3. BIGNUM_DTOA_SHORTEST, // Same as BIGNUM_DTOA_SHORTEST but for single-precision floats. BIGNUM_DTOA_SHORTEST_SINGLE, // Return a fixed number of digits after the decimal point. // For instance fixed(0.1, 4) becomes 0.1000 // If the input number is big, the output will be big. BIGNUM_DTOA_FIXED, // Return a fixed number of digits, no matter what the exponent is. BIGNUM_DTOA_PRECISION }; // Converts the given double 'v' to ascii. // The result should be interpreted as buffer * 10^(point-length). // The buffer will be null-terminated. // // The input v must be > 0 and different from NaN, and Infinity. // // The output depends on the given mode: // - SHORTEST: produce the least amount of digits for which the internal // identity requirement is still satisfied. If the digits are printed // (together with the correct exponent) then reading this number will give // 'v' again. The buffer will choose the representation that is closest to // 'v'. If there are two at the same distance, than the number is round up. // In this mode the 'requested_digits' parameter is ignored. // - FIXED: produces digits necessary to print a given number with // 'requested_digits' digits after the decimal point. The produced digits // might be too short in which case the caller has to fill the gaps with '0's. // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. // Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns // buffer="2", point=0. // Note: the length of the returned buffer has no meaning wrt the significance // of its digits. That is, just because it contains '0's does not mean that // any other digit would not satisfy the internal identity requirement. // - PRECISION: produces 'requested_digits' where the first digit is not '0'. // Even though the length of produced digits usually equals // 'requested_digits', the function is allowed to return fewer digits, in // which case the caller has to fill the missing digits with '0's. // Halfway cases are again rounded up. // 'BignumDtoa' expects the given buffer to be big enough to hold all digits // and a terminating null-character. void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits, Vector<char> buffer, int* length, int* point); } // namespace double_conversion #endif // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/diy-fp.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_DIY_FP_H_ #define DOUBLE_CONVERSION_DIY_FP_H_ #include "utils.h" namespace double_conversion { // This "Do It Yourself Floating Point" class implements a floating-point number // with a uint64 significand and an int exponent. Normalized DiyFp numbers will // have the most significant bit of the significand set. // Multiplication and Subtraction do not normalize their results. // DiyFp are not designed to contain special doubles (NaN and Infinity). class DiyFp { public: static const int kSignificandSize = 64; DiyFp() : f_(0), e_(0) {} DiyFp(uint64_t significand, int exponent) : f_(significand), e_(exponent) {} // this = this - other. // The exponents of both numbers must be the same and the significand of this // must be bigger than the significand of other. // The result will not be normalized. void Subtract(const DiyFp& other) { ASSERT(e_ == other.e_); ASSERT(f_ >= other.f_); f_ -= other.f_; } // Returns a - b. // The exponents of both numbers must be the same and this must be bigger // than other. The result will not be normalized. static DiyFp Minus(const DiyFp& a, const DiyFp& b) { DiyFp result = a; result.Subtract(b); return result; } // this = this * other. void Multiply(const DiyFp& other); // returns a * b; static DiyFp Times(const DiyFp& a, const DiyFp& b) { DiyFp result = a; result.Multiply(b); return result; } void Normalize() { ASSERT(f_ != 0); uint64_t significand = f_; int exponent = e_; // This method is mainly called for normalizing boundaries. In general // boundaries need to be shifted by 10 bits. We thus optimize for this case. const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000); while ((significand & k10MSBits) == 0) { significand <<= 10; exponent -= 10; } while ((significand & kUint64MSB) == 0) { significand <<= 1; exponent--; } f_ = significand; e_ = exponent; } static DiyFp Normalize(const DiyFp& a) { DiyFp result = a; result.Normalize(); return result; } uint64_t f() const { return f_; } int e() const { return e_; } void set_f(uint64_t new_value) { f_ = new_value; } void set_e(int new_value) { e_ = new_value; } private: static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000); uint64_t f_; int e_; }; } // namespace double_conversion #endif // DOUBLE_CONVERSION_DIY_FP_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/fixed-dtoa.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_FIXED_DTOA_H_ #define DOUBLE_CONVERSION_FIXED_DTOA_H_ #include "utils.h" namespace double_conversion { // Produces digits necessary to print a given number with // 'fractional_count' digits after the decimal point. // The buffer must be big enough to hold the result plus one terminating null // character. // // The produced digits might be too short in which case the caller has to fill // the gaps with '0's. // Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and // decimal_point = -2. // Halfway cases are rounded towards +/-Infinity (away from 0). The call // FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0. // The returned buffer may contain digits that would be truncated from the // shortest representation of the input. // // This method only works for some parameters. If it can't handle the input it // returns false. The output is null-terminated when the function succeeds. bool FastFixedDtoa(double v, int fractional_count, Vector<char> buffer, int* length, int* decimal_point); } // namespace double_conversion #endif // DOUBLE_CONVERSION_FIXED_DTOA_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/strtod.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_STRTOD_H_ #define DOUBLE_CONVERSION_STRTOD_H_ #include "utils.h" namespace double_conversion { // The buffer must only contain digits in the range [0-9]. It must not // contain a dot or a sign. It must not start with '0', and must not be empty. double Strtod(Vector<const char> buffer, int exponent); // The buffer must only contain digits in the range [0-9]. It must not // contain a dot or a sign. It must not start with '0', and must not be empty. float Strtof(Vector<const char> buffer, int exponent); } // namespace double_conversion #endif // DOUBLE_CONVERSION_STRTOD_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/utils.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_UTILS_H_ #define DOUBLE_CONVERSION_UTILS_H_ #include <stdlib.h> #include <string.h> #include <assert.h> #ifndef ASSERT #define ASSERT(condition) \ assert(condition); #endif #ifndef UNIMPLEMENTED #define UNIMPLEMENTED() (abort()) #endif #ifndef DOUBLE_CONVERSION_NO_RETURN #ifdef _MSC_VER #define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn) #else #define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn)) #endif #endif #ifndef UNREACHABLE #ifdef _MSC_VER void DOUBLE_CONVERSION_NO_RETURN abort_noreturn(); inline void abort_noreturn() { abort(); } #define UNREACHABLE() (abort_noreturn()) #else #define UNREACHABLE() (abort()) #endif #endif // Double operations detection based on target architecture. // Linux uses a 80bit wide floating point stack on x86. This induces double // rounding, which in turn leads to wrong results. // An easy way to test if the floating-point operations are correct is to // evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then // the result is equal to 89255e-22. // The best way to test this, is to create a division-function and to compare // the output of the division with the expected result. (Inlining must be // disabled.) // On Linux,x86 89255e-22 != Div_double(89255.0/1e22) #if defined(_M_X64) || defined(__x86_64__) || \ defined(__ARMEL__) || defined(__avr32__) || \ defined(__hppa__) || defined(__ia64__) || \ defined(__mips__) || \ defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \ defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \ defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ defined(__SH4__) || defined(__alpha__) || \ defined(_MIPS_ARCH_MIPS32R2) || \ defined(__AARCH64EL__) || defined(__aarch64__) || \ defined(__riscv) #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 #elif defined(__mc68000__) #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS #elif defined(_M_IX86) || defined(__i386__) || defined(__i386) #if defined(_WIN32) // Windows uses a 64bit wide floating point stack. #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 #else #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS #endif // _WIN32 #else #error Target architecture was not detected as supported by Double-Conversion. #endif #if defined(__GNUC__) #define DOUBLE_CONVERSION_UNUSED __attribute__((unused)) #else #define DOUBLE_CONVERSION_UNUSED #endif #if defined(_WIN32) && !defined(__MINGW32__) typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; // NOLINT typedef unsigned short uint16_t; // NOLINT typedef int int32_t; typedef unsigned int uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; // intptr_t and friends are defined in crtdefs.h through stdio.h. #else #include <stdint.h> #endif typedef uint16_t uc16; // The following macro works on both 32 and 64-bit platforms. // Usage: instead of writing 0x1234567890123456 // write UINT64_2PART_C(0x12345678,90123456); #define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u)) // The expression ARRAY_SIZE(a) is a compile-time constant of type // size_t which represents the number of elements of the given // array. You should only use ARRAY_SIZE on statically allocated // arrays. #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) #endif // A macro to disallow the evil copy constructor and operator= functions // This should be used in the private: declarations for a class #ifndef DISALLOW_COPY_AND_ASSIGN #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #endif // A macro to disallow all the implicit constructors, namely the // default constructor, copy constructor and operator= functions. // // This should be used in the private: declarations for a class // that wants to prevent anyone from instantiating it. This is // especially useful for classes containing only static methods. #ifndef DISALLOW_IMPLICIT_CONSTRUCTORS #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ TypeName(); \ DISALLOW_COPY_AND_ASSIGN(TypeName) #endif namespace double_conversion { static const int kCharSize = sizeof(char); // Returns the maximum of the two parameters. template <typename T> static T Max(T a, T b) { return a < b ? b : a; } // Returns the minimum of the two parameters. template <typename T> static T Min(T a, T b) { return a < b ? a : b; } inline int StrLength(const char* string) { size_t length = strlen(string); ASSERT(length == static_cast<size_t>(static_cast<int>(length))); return static_cast<int>(length); } // This is a simplified version of V8's Vector class. template <typename T> class Vector { public: Vector() : start_(NULL), length_(0) {} Vector(T* data, int len) : start_(data), length_(len) { ASSERT(len == 0 || (len > 0 && data != NULL)); } // Returns a vector using the same backing storage as this one, // spanning from and including 'from', to but not including 'to'. Vector<T> SubVector(int from, int to) { ASSERT(to <= length_); ASSERT(from < to); ASSERT(0 <= from); return Vector<T>(start() + from, to - from); } // Returns the length of the vector. int length() const { return length_; } // Returns whether or not the vector is empty. bool is_empty() const { return length_ == 0; } // Returns the pointer to the start of the data in the vector. T* start() const { return start_; } // Access individual vector elements - checks bounds in debug mode. T& operator[](int index) const { ASSERT(0 <= index && index < length_); return start_[index]; } T& first() { return start_[0]; } T& last() { return start_[length_ - 1]; } private: T* start_; int length_; }; // Helper class for building result strings in a character buffer. The // purpose of the class is to use safe operations that checks the // buffer bounds on all operations in debug mode. class StringBuilder { public: StringBuilder(char* buffer, int buffer_size) : buffer_(buffer, buffer_size), position_(0) { } ~StringBuilder() { if (!is_finalized()) Finalize(); } int size() const { return buffer_.length(); } // Get the current position in the builder. int position() const { ASSERT(!is_finalized()); return position_; } // Reset the position. void Reset() { position_ = 0; } // Add a single character to the builder. It is not allowed to add // 0-characters; use the Finalize() method to terminate the string // instead. void AddCharacter(char c) { ASSERT(c != '\0'); ASSERT(!is_finalized() && position_ < buffer_.length()); buffer_[position_++] = c; } // Add an entire string to the builder. Uses strlen() internally to // compute the length of the input string. void AddString(const char* s) { AddSubstring(s, StrLength(s)); } // Add the first 'n' characters of the given string 's' to the // builder. The input string must have enough characters. void AddSubstring(const char* s, int n) { ASSERT(!is_finalized() && position_ + n < buffer_.length()); ASSERT(static_cast<size_t>(n) <= strlen(s)); memmove(&buffer_[position_], s, n * kCharSize); position_ += n; } // Add character padding to the builder. If count is non-positive, // nothing is added to the builder. void AddPadding(char c, int count) { for (int i = 0; i < count; i++) { AddCharacter(c); } } // Finalize the string by 0-terminating it and returning the buffer. char* Finalize() { ASSERT(!is_finalized() && position_ < buffer_.length()); buffer_[position_] = '\0'; // Make sure nobody managed to add a 0-character to the // buffer while building the string. ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_)); position_ = -1; ASSERT(is_finalized()); return buffer_.start(); } private: Vector<char> buffer_; int position_; bool is_finalized() const { return position_ < 0; } DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder); }; // The type-based aliasing rule allows the compiler to assume that pointers of // different types (for some definition of different) never alias each other. // Thus the following code does not work: // // float f = foo(); // int fbits = *(int*)(&f); // // The compiler 'knows' that the int pointer can't refer to f since the types // don't match, so the compiler may cache f in a register, leaving random data // in fbits. Using C++ style casts makes no difference, however a pointer to // char data is assumed to alias any other pointer. This is the 'memcpy // exception'. // // Bit_cast uses the memcpy exception to move the bits from a variable of one // type of a variable of another type. Of course the end result is likely to // be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) // will completely optimize BitCast away. // // There is an additional use for BitCast. // Recent gccs will warn when they see casts that may result in breakage due to // the type-based aliasing rule. If you have checked that there is no breakage // you can use BitCast to cast one pointer type to another. This confuses gcc // enough that it can no longer see that you have cast one pointer type to // another thus avoiding the warning. template <class Dest, class Source> inline Dest BitCast(const Source& source) { // Compile time assertion: sizeof(Dest) == sizeof(Source) // A compile error here means your Dest and Source have different sizes. DOUBLE_CONVERSION_UNUSED typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1]; Dest dest; memmove(&dest, &source, sizeof(dest)); return dest; } template <class Dest, class Source> inline Dest BitCast(Source* source) { return BitCast<Dest>(reinterpret_cast<uintptr_t>(source)); } } // namespace double_conversion #endif // DOUBLE_CONVERSION_UTILS_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/CMakeLists.txt
set(headers bignum.h cached-powers.h diy-fp.h double-conversion.h fast-dtoa.h fixed-dtoa.h ieee.h strtod.h utils.h ) add_library(double-conversion bignum.cc bignum-dtoa.cc cached-powers.cc diy-fp.cc double-conversion.cc fast-dtoa.cc fixed-dtoa.cc strtod.cc ${headers} ) target_include_directories(double-conversion PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>) # Add fPIC on x86_64 when supported. include(CheckCXXCompilerFlag) check_cxx_compiler_flag(-fPIC CXX_HAS_FPIC) if(CXX_HAS_FPIC AND CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") set_target_properties(double-conversion PROPERTIES COMPILE_FLAGS "-fPIC") endif() # # associates the list of headers with the library # for the purposes of installation/import into other projects set_target_properties(double-conversion PROPERTIES PUBLIC_HEADER "${headers}") if (BUILD_SHARED_LIBS) set_target_properties(double-conversion PROPERTIES VERSION ${double-conversion_SOVERSION} SOVERSION ${double-conversion_SOVERSION_MAJOR}) endif() # # install command to set up library install # given the above PUBLIC_HEADER property set, this # pulls along all the header files with the library. install(TARGETS double-conversion EXPORT double-conversionLibraryDepends RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT bin LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT shlib ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT lib PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/double-conversion" COMPONENT dev)
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/fast-dtoa.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_FAST_DTOA_H_ #define DOUBLE_CONVERSION_FAST_DTOA_H_ #include "utils.h" namespace double_conversion { enum FastDtoaMode { // Computes the shortest representation of the given input. The returned // result will be the most accurate number of this length. Longer // representations might be more accurate. FAST_DTOA_SHORTEST, // Same as FAST_DTOA_SHORTEST but for single-precision floats. FAST_DTOA_SHORTEST_SINGLE, // Computes a representation where the precision (number of digits) is // given as input. The precision is independent of the decimal point. FAST_DTOA_PRECISION }; // FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not // include the terminating '\0' character. static const int kFastDtoaMaximalLength = 17; // Same for single-precision numbers. static const int kFastDtoaMaximalSingleLength = 9; // Provides a decimal representation of v. // The result should be interpreted as buffer * 10^(point - length). // // Precondition: // * v must be a strictly positive finite double. // // Returns true if it succeeds, otherwise the result can not be trusted. // There will be *length digits inside the buffer followed by a null terminator. // If the function returns true and mode equals // - FAST_DTOA_SHORTEST, then // the parameter requested_digits is ignored. // The result satisfies // v == (double) (buffer * 10^(point - length)). // The digits in the buffer are the shortest representation possible. E.g. // if 0.099999999999 and 0.1 represent the same double then "1" is returned // with point = 0. // The last digit will be closest to the actual v. That is, even if several // digits might correctly yield 'v' when read again, the buffer will contain // the one closest to v. // - FAST_DTOA_PRECISION, then // the buffer contains requested_digits digits. // the difference v - (buffer * 10^(point-length)) is closest to zero for // all possible representations of requested_digits digits. // If there are two values that are equally close, then FastDtoa returns // false. // For both modes the buffer must be large enough to hold the result. bool FastDtoa(double d, FastDtoaMode mode, int requested_digits, Vector<char> buffer, int* length, int* decimal_point); } // namespace double_conversion #endif // DOUBLE_CONVERSION_FAST_DTOA_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/bignum.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_BIGNUM_H_ #define DOUBLE_CONVERSION_BIGNUM_H_ #include "utils.h" namespace double_conversion { class Bignum { public: // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately. // This bignum can encode much bigger numbers, since it contains an // exponent. static const int kMaxSignificantBits = 3584; Bignum(); void AssignUInt16(uint16_t value); void AssignUInt64(uint64_t value); void AssignBignum(const Bignum& other); void AssignDecimalString(Vector<const char> value); void AssignHexString(Vector<const char> value); void AssignPowerUInt16(uint16_t base, int exponent); void AddUInt64(uint64_t operand); void AddBignum(const Bignum& other); // Precondition: this >= other. void SubtractBignum(const Bignum& other); void Square(); void ShiftLeft(int shift_amount); void MultiplyByUInt32(uint32_t factor); void MultiplyByUInt64(uint64_t factor); void MultiplyByPowerOfTen(int exponent); void Times10() { return MultiplyByUInt32(10); } // Pseudocode: // int result = this / other; // this = this % other; // In the worst case this function is in O(this/other). uint16_t DivideModuloIntBignum(const Bignum& other); bool ToHexString(char* buffer, int buffer_size) const; // Returns // -1 if a < b, // 0 if a == b, and // +1 if a > b. static int Compare(const Bignum& a, const Bignum& b); static bool Equal(const Bignum& a, const Bignum& b) { return Compare(a, b) == 0; } static bool LessEqual(const Bignum& a, const Bignum& b) { return Compare(a, b) <= 0; } static bool Less(const Bignum& a, const Bignum& b) { return Compare(a, b) < 0; } // Returns Compare(a + b, c); static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c); // Returns a + b == c static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) { return PlusCompare(a, b, c) == 0; } // Returns a + b <= c static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) { return PlusCompare(a, b, c) <= 0; } // Returns a + b < c static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) { return PlusCompare(a, b, c) < 0; } private: typedef uint32_t Chunk; typedef uint64_t DoubleChunk; static const int kChunkSize = sizeof(Chunk) * 8; static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8; // With bigit size of 28 we loose some bits, but a double still fits easily // into two chunks, and more importantly we can use the Comba multiplication. static const int kBigitSize = 28; static const Chunk kBigitMask = (1 << kBigitSize) - 1; // Every instance allocates kBigitLength chunks on the stack. Bignums cannot // grow. There are no checks if the stack-allocated space is sufficient. static const int kBigitCapacity = kMaxSignificantBits / kBigitSize; void EnsureCapacity(int size) { if (size > kBigitCapacity) { UNREACHABLE(); } } void Align(const Bignum& other); void Clamp(); bool IsClamped() const; void Zero(); // Requires this to have enough capacity (no tests done). // Updates used_digits_ if necessary. // shift_amount must be < kBigitSize. void BigitsShiftLeft(int shift_amount); // BigitLength includes the "hidden" digits encoded in the exponent. int BigitLength() const { return used_digits_ + exponent_; } Chunk BigitAt(int index) const; void SubtractTimes(const Bignum& other, int factor); Chunk bigits_buffer_[kBigitCapacity]; // A vector backed by bigits_buffer_. This way accesses to the array are // checked for out-of-bounds errors. Vector<Chunk> bigits_; int used_digits_; // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize). int exponent_; DISALLOW_COPY_AND_ASSIGN(Bignum); }; } // namespace double_conversion #endif // DOUBLE_CONVERSION_BIGNUM_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/cached-powers.h
// Copyright 2010 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_CACHED_POWERS_H_ #define DOUBLE_CONVERSION_CACHED_POWERS_H_ #include "diy-fp.h" namespace double_conversion { class PowersOfTenCache { public: // Not all powers of ten are cached. The decimal exponent of two neighboring // cached numbers will differ by kDecimalExponentDistance. static const int kDecimalExponentDistance; static const int kMinDecimalExponent; static const int kMaxDecimalExponent; // Returns a cached power-of-ten with a binary exponent in the range // [min_exponent; max_exponent] (boundaries included). static void GetCachedPowerForBinaryExponentRange(int min_exponent, int max_exponent, DiyFp* power, int* decimal_exponent); // Returns a cached power of ten x ~= 10^k such that // k <= decimal_exponent < k + kCachedPowersDecimalDistance. // The given decimal_exponent must satisfy // kMinDecimalExponent <= requested_exponent, and // requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance. static void GetCachedPowerForDecimalExponent(int requested_exponent, DiyFp* power, int* found_exponent); }; } // namespace double_conversion #endif // DOUBLE_CONVERSION_CACHED_POWERS_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/ieee.h
// Copyright 2012 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_DOUBLE_H_ #define DOUBLE_CONVERSION_DOUBLE_H_ #include "diy-fp.h" namespace double_conversion { // We assume that doubles and uint64_t have the same endianness. static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); } static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); } static uint32_t float_to_uint32(float f) { return BitCast<uint32_t>(f); } static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); } // Helper functions for doubles. class Double { public: static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000); static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000); static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF); static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000); static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit. static const int kSignificandSize = 53; Double() : d64_(0) {} explicit Double(double d) : d64_(double_to_uint64(d)) {} explicit Double(uint64_t d64) : d64_(d64) {} explicit Double(DiyFp diy_fp) : d64_(DiyFpToUint64(diy_fp)) {} // The value encoded by this Double must be greater or equal to +0.0. // It must not be special (infinity, or NaN). DiyFp AsDiyFp() const { ASSERT(Sign() > 0); ASSERT(!IsSpecial()); return DiyFp(Significand(), Exponent()); } // The value encoded by this Double must be strictly greater than 0. DiyFp AsNormalizedDiyFp() const { ASSERT(value() > 0.0); uint64_t f = Significand(); int e = Exponent(); // The current double could be a denormal. while ((f & kHiddenBit) == 0) { f <<= 1; e--; } // Do the final shifts in one go. f <<= DiyFp::kSignificandSize - kSignificandSize; e -= DiyFp::kSignificandSize - kSignificandSize; return DiyFp(f, e); } // Returns the double's bit as uint64. uint64_t AsUint64() const { return d64_; } // Returns the next greater double. Returns +infinity on input +infinity. double NextDouble() const { if (d64_ == kInfinity) return Double(kInfinity).value(); if (Sign() < 0 && Significand() == 0) { // -0.0 return 0.0; } if (Sign() < 0) { return Double(d64_ - 1).value(); } else { return Double(d64_ + 1).value(); } } double PreviousDouble() const { if (d64_ == (kInfinity | kSignMask)) return -Infinity(); if (Sign() < 0) { return Double(d64_ + 1).value(); } else { if (Significand() == 0) return -0.0; return Double(d64_ - 1).value(); } } int Exponent() const { if (IsDenormal()) return kDenormalExponent; uint64_t d64 = AsUint64(); int biased_e = static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize); return biased_e - kExponentBias; } uint64_t Significand() const { uint64_t d64 = AsUint64(); uint64_t significand = d64 & kSignificandMask; if (!IsDenormal()) { return significand + kHiddenBit; } else { return significand; } } // Returns true if the double is a denormal. bool IsDenormal() const { uint64_t d64 = AsUint64(); return (d64 & kExponentMask) == 0; } // We consider denormals not to be special. // Hence only Infinity and NaN are special. bool IsSpecial() const { uint64_t d64 = AsUint64(); return (d64 & kExponentMask) == kExponentMask; } bool IsNan() const { uint64_t d64 = AsUint64(); return ((d64 & kExponentMask) == kExponentMask) && ((d64 & kSignificandMask) != 0); } bool IsInfinite() const { uint64_t d64 = AsUint64(); return ((d64 & kExponentMask) == kExponentMask) && ((d64 & kSignificandMask) == 0); } int Sign() const { uint64_t d64 = AsUint64(); return (d64 & kSignMask) == 0? 1: -1; } // Precondition: the value encoded by this Double must be greater or equal // than +0.0. DiyFp UpperBoundary() const { ASSERT(Sign() > 0); return DiyFp(Significand() * 2 + 1, Exponent() - 1); } // Computes the two boundaries of this. // The bigger boundary (m_plus) is normalized. The lower boundary has the same // exponent as m_plus. // Precondition: the value encoded by this Double must be greater than 0. void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const { ASSERT(value() > 0.0); DiyFp v = this->AsDiyFp(); DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1)); DiyFp m_minus; if (LowerBoundaryIsCloser()) { m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2); } else { m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1); } m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e())); m_minus.set_e(m_plus.e()); *out_m_plus = m_plus; *out_m_minus = m_minus; } bool LowerBoundaryIsCloser() const { // The boundary is closer if the significand is of the form f == 2^p-1 then // the lower boundary is closer. // Think of v = 1000e10 and v- = 9999e9. // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but // at a distance of 1e8. // The only exception is for the smallest normal: the largest denormal is // at the same distance as its successor. // Note: denormals have the same exponent as the smallest normals. bool physical_significand_is_zero = ((AsUint64() & kSignificandMask) == 0); return physical_significand_is_zero && (Exponent() != kDenormalExponent); } double value() const { return uint64_to_double(d64_); } // Returns the significand size for a given order of magnitude. // If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude. // This function returns the number of significant binary digits v will have // once it's encoded into a double. In almost all cases this is equal to // kSignificandSize. The only exceptions are denormals. They start with // leading zeroes and their effective significand-size is hence smaller. static int SignificandSizeForOrderOfMagnitude(int order) { if (order >= (kDenormalExponent + kSignificandSize)) { return kSignificandSize; } if (order <= kDenormalExponent) return 0; return order - kDenormalExponent; } static double Infinity() { return Double(kInfinity).value(); } static double NaN() { return Double(kNaN).value(); } private: static const int kExponentBias = 0x3FF + kPhysicalSignificandSize; static const int kDenormalExponent = -kExponentBias + 1; static const int kMaxExponent = 0x7FF - kExponentBias; static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000); static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000); const uint64_t d64_; static uint64_t DiyFpToUint64(DiyFp diy_fp) { uint64_t significand = diy_fp.f(); int exponent = diy_fp.e(); while (significand > kHiddenBit + kSignificandMask) { significand >>= 1; exponent++; } if (exponent >= kMaxExponent) { return kInfinity; } if (exponent < kDenormalExponent) { return 0; } while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) { significand <<= 1; exponent--; } uint64_t biased_exponent; if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) { biased_exponent = 0; } else { biased_exponent = static_cast<uint64_t>(exponent + kExponentBias); } return (significand & kSignificandMask) | (biased_exponent << kPhysicalSignificandSize); } DISALLOW_COPY_AND_ASSIGN(Double); }; class Single { public: static const uint32_t kSignMask = 0x80000000; static const uint32_t kExponentMask = 0x7F800000; static const uint32_t kSignificandMask = 0x007FFFFF; static const uint32_t kHiddenBit = 0x00800000; static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit. static const int kSignificandSize = 24; Single() : d32_(0) {} explicit Single(float f) : d32_(float_to_uint32(f)) {} explicit Single(uint32_t d32) : d32_(d32) {} // The value encoded by this Single must be greater or equal to +0.0. // It must not be special (infinity, or NaN). DiyFp AsDiyFp() const { ASSERT(Sign() > 0); ASSERT(!IsSpecial()); return DiyFp(Significand(), Exponent()); } // Returns the single's bit as uint64. uint32_t AsUint32() const { return d32_; } int Exponent() const { if (IsDenormal()) return kDenormalExponent; uint32_t d32 = AsUint32(); int biased_e = static_cast<int>((d32 & kExponentMask) >> kPhysicalSignificandSize); return biased_e - kExponentBias; } uint32_t Significand() const { uint32_t d32 = AsUint32(); uint32_t significand = d32 & kSignificandMask; if (!IsDenormal()) { return significand + kHiddenBit; } else { return significand; } } // Returns true if the single is a denormal. bool IsDenormal() const { uint32_t d32 = AsUint32(); return (d32 & kExponentMask) == 0; } // We consider denormals not to be special. // Hence only Infinity and NaN are special. bool IsSpecial() const { uint32_t d32 = AsUint32(); return (d32 & kExponentMask) == kExponentMask; } bool IsNan() const { uint32_t d32 = AsUint32(); return ((d32 & kExponentMask) == kExponentMask) && ((d32 & kSignificandMask) != 0); } bool IsInfinite() const { uint32_t d32 = AsUint32(); return ((d32 & kExponentMask) == kExponentMask) && ((d32 & kSignificandMask) == 0); } int Sign() const { uint32_t d32 = AsUint32(); return (d32 & kSignMask) == 0? 1: -1; } // Computes the two boundaries of this. // The bigger boundary (m_plus) is normalized. The lower boundary has the same // exponent as m_plus. // Precondition: the value encoded by this Single must be greater than 0. void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const { ASSERT(value() > 0.0); DiyFp v = this->AsDiyFp(); DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1)); DiyFp m_minus; if (LowerBoundaryIsCloser()) { m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2); } else { m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1); } m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e())); m_minus.set_e(m_plus.e()); *out_m_plus = m_plus; *out_m_minus = m_minus; } // Precondition: the value encoded by this Single must be greater or equal // than +0.0. DiyFp UpperBoundary() const { ASSERT(Sign() > 0); return DiyFp(Significand() * 2 + 1, Exponent() - 1); } bool LowerBoundaryIsCloser() const { // The boundary is closer if the significand is of the form f == 2^p-1 then // the lower boundary is closer. // Think of v = 1000e10 and v- = 9999e9. // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but // at a distance of 1e8. // The only exception is for the smallest normal: the largest denormal is // at the same distance as its successor. // Note: denormals have the same exponent as the smallest normals. bool physical_significand_is_zero = ((AsUint32() & kSignificandMask) == 0); return physical_significand_is_zero && (Exponent() != kDenormalExponent); } float value() const { return uint32_to_float(d32_); } static float Infinity() { return Single(kInfinity).value(); } static float NaN() { return Single(kNaN).value(); } private: static const int kExponentBias = 0x7F + kPhysicalSignificandSize; static const int kDenormalExponent = -kExponentBias + 1; static const int kMaxExponent = 0xFF - kExponentBias; static const uint32_t kInfinity = 0x7F800000; static const uint32_t kNaN = 0x7FC00000; const uint32_t d32_; DISALLOW_COPY_AND_ASSIGN(Single); }; } // namespace double_conversion #endif // DOUBLE_CONVERSION_DOUBLE_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/double-conversion/double-conversion.h
// Copyright 2012 the V8 project authors. All rights reserved. // 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. #ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ #define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ #include "utils.h" namespace double_conversion { class DoubleToStringConverter { public: // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the // function returns false. static const int kMaxFixedDigitsBeforePoint = 60; static const int kMaxFixedDigitsAfterPoint = 60; // When calling ToExponential with a requested_digits // parameter > kMaxExponentialDigits then the function returns false. static const int kMaxExponentialDigits = 120; // When calling ToPrecision with a requested_digits // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits // then the function returns false. static const int kMinPrecisionDigits = 1; static const int kMaxPrecisionDigits = 120; enum Flags { NO_FLAGS = 0, EMIT_POSITIVE_EXPONENT_SIGN = 1, EMIT_TRAILING_DECIMAL_POINT = 2, EMIT_TRAILING_ZERO_AFTER_POINT = 4, UNIQUE_ZERO = 8 }; // Flags should be a bit-or combination of the possible Flags-enum. // - NO_FLAGS: no special flags. // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent // form, emits a '+' for positive exponents. Example: 1.2e+2. // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is // converted into decimal format then a trailing decimal point is appended. // Example: 2345.0 is converted to "2345.". // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point // emits a trailing '0'-character. This flag requires the // EXMIT_TRAILING_DECIMAL_POINT flag. // Example: 2345.0 is converted to "2345.0". // - UNIQUE_ZERO: "-0.0" is converted to "0.0". // // Infinity symbol and nan_symbol provide the string representation for these // special values. If the string is NULL and the special value is encountered // then the conversion functions return false. // // The exponent_character is used in exponential representations. It is // usually 'e' or 'E'. // // When converting to the shortest representation the converter will // represent input numbers in decimal format if they are in the interval // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[ // (lower boundary included, greater boundary excluded). // Example: with decimal_in_shortest_low = -6 and // decimal_in_shortest_high = 21: // ToShortest(0.000001) -> "0.000001" // ToShortest(0.0000001) -> "1e-7" // ToShortest(111111111111111111111.0) -> "111111111111111110000" // ToShortest(100000000000000000000.0) -> "100000000000000000000" // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" // // When converting to precision mode the converter may add // max_leading_padding_zeroes before returning the number in exponential // format. // Example with max_leading_padding_zeroes_in_precision_mode = 6. // ToPrecision(0.0000012345, 2) -> "0.0000012" // ToPrecision(0.00000012345, 2) -> "1.2e-7" // Similarily the converter may add up to // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid // returning an exponential representation. A zero added by the // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: // ToPrecision(230.0, 2) -> "230" // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. DoubleToStringConverter(int flags, const char* infinity_symbol, const char* nan_symbol, char exponent_character, int decimal_in_shortest_low, int decimal_in_shortest_high, int max_leading_padding_zeroes_in_precision_mode, int max_trailing_padding_zeroes_in_precision_mode) : flags_(flags), infinity_symbol_(infinity_symbol), nan_symbol_(nan_symbol), exponent_character_(exponent_character), decimal_in_shortest_low_(decimal_in_shortest_low), decimal_in_shortest_high_(decimal_in_shortest_high), max_leading_padding_zeroes_in_precision_mode_( max_leading_padding_zeroes_in_precision_mode), max_trailing_padding_zeroes_in_precision_mode_( max_trailing_padding_zeroes_in_precision_mode) { // When 'trailing zero after the point' is set, then 'trailing point' // must be set too. ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) || !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0)); } // Returns a converter following the EcmaScript specification. static const DoubleToStringConverter& EcmaScriptConverter(); // Computes the shortest string of digits that correctly represent the input // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high // (see constructor) it then either returns a decimal representation, or an // exponential representation. // Example with decimal_in_shortest_low = -6, // decimal_in_shortest_high = 21, // EMIT_POSITIVE_EXPONENT_SIGN activated, and // EMIT_TRAILING_DECIMAL_POINT deactived: // ToShortest(0.000001) -> "0.000001" // ToShortest(0.0000001) -> "1e-7" // ToShortest(111111111111111111111.0) -> "111111111111111110000" // ToShortest(100000000000000000000.0) -> "100000000000000000000" // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" // // Note: the conversion may round the output if the returned string // is accurate enough to uniquely identify the input-number. // For example the most precise representation of the double 9e59 equals // "899999999999999918767229449717619953810131273674690656206848", but // the converter will return the shorter (but still correct) "9e59". // // Returns true if the conversion succeeds. The conversion always succeeds // except when the input value is special and no infinity_symbol or // nan_symbol has been given to the constructor. bool ToShortest(double value, StringBuilder* result_builder) const { return ToShortestIeeeNumber(value, result_builder, SHORTEST); } // Same as ToShortest, but for single-precision floats. bool ToShortestSingle(float value, StringBuilder* result_builder) const { return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE); } // Computes a decimal representation with a fixed number of digits after the // decimal point. The last emitted digit is rounded. // // Examples: // ToFixed(3.12, 1) -> "3.1" // ToFixed(3.1415, 3) -> "3.142" // ToFixed(1234.56789, 4) -> "1234.5679" // ToFixed(1.23, 5) -> "1.23000" // ToFixed(0.1, 4) -> "0.1000" // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00" // ToFixed(0.1, 30) -> "0.100000000000000005551115123126" // ToFixed(0.1, 17) -> "0.10000000000000001" // // If requested_digits equals 0, then the tail of the result depends on // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT. // Examples, for requested_digits == 0, // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be // - false and false: then 123.45 -> 123 // 0.678 -> 1 // - true and false: then 123.45 -> 123. // 0.678 -> 1. // - true and true: then 123.45 -> 123.0 // 0.678 -> 1.0 // // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - 'value' > 10^kMaxFixedDigitsBeforePoint, or // - 'requested_digits' > kMaxFixedDigitsAfterPoint. // The last two conditions imply that the result will never contain more than // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters // (one additional character for the sign, and one for the decimal point). bool ToFixed(double value, int requested_digits, StringBuilder* result_builder) const; // Computes a representation in exponential format with requested_digits // after the decimal point. The last emitted digit is rounded. // If requested_digits equals -1, then the shortest exponential representation // is computed. // // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and // exponent_character set to 'e'. // ToExponential(3.12, 1) -> "3.1e0" // ToExponential(5.0, 3) -> "5.000e0" // ToExponential(0.001, 2) -> "1.00e-3" // ToExponential(3.1415, -1) -> "3.1415e0" // ToExponential(3.1415, 4) -> "3.1415e0" // ToExponential(3.1415, 3) -> "3.142e0" // ToExponential(123456789000000, 3) -> "1.235e14" // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30" // ToExponential(1000000000000000019884624838656.0, 32) -> // "1.00000000000000001988462483865600e30" // ToExponential(1234, 0) -> "1e3" // // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - 'requested_digits' > kMaxExponentialDigits. // The last condition implies that the result will never contain more than // kMaxExponentialDigits + 8 characters (the sign, the digit before the // decimal point, the decimal point, the exponent character, the // exponent's sign, and at most 3 exponent digits). bool ToExponential(double value, int requested_digits, StringBuilder* result_builder) const; // Computes 'precision' leading digits of the given 'value' and returns them // either in exponential or decimal format, depending on // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the // constructor). // The last computed digit is rounded. // // Example with max_leading_padding_zeroes_in_precision_mode = 6. // ToPrecision(0.0000012345, 2) -> "0.0000012" // ToPrecision(0.00000012345, 2) -> "1.2e-7" // Similarily the converter may add up to // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid // returning an exponential representation. A zero added by the // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: // ToPrecision(230.0, 2) -> "230" // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no // EMIT_TRAILING_ZERO_AFTER_POINT: // ToPrecision(123450.0, 6) -> "123450" // ToPrecision(123450.0, 5) -> "123450" // ToPrecision(123450.0, 4) -> "123500" // ToPrecision(123450.0, 3) -> "123000" // ToPrecision(123450.0, 2) -> "1.2e5" // // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - precision < kMinPericisionDigits // - precision > kMaxPrecisionDigits // The last condition implies that the result will never contain more than // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the // exponent character, the exponent's sign, and at most 3 exponent digits). bool ToPrecision(double value, int precision, StringBuilder* result_builder) const; enum DtoaMode { // Produce the shortest correct representation. // For example the output of 0.299999999999999988897 is (the less accurate // but correct) 0.3. SHORTEST, // Same as SHORTEST, but for single-precision floats. SHORTEST_SINGLE, // Produce a fixed number of digits after the decimal point. // For instance fixed(0.1, 4) becomes 0.1000 // If the input number is big, the output will be big. FIXED, // Fixed number of digits (independent of the decimal point). PRECISION }; // The maximal number of digits that are needed to emit a double in base 10. // A higher precision can be achieved by using more digits, but the shortest // accurate representation of any double will never use more digits than // kBase10MaximalLength. // Note that DoubleToAscii null-terminates its input. So the given buffer // should be at least kBase10MaximalLength + 1 characters long. static const int kBase10MaximalLength = 17; // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v' // after it has been casted to a single-precision float. That is, in this // mode static_cast<float>(v) must not be NaN, +Infinity or -Infinity. // // The result should be interpreted as buffer * 10^(point-length). // // The output depends on the given mode: // - SHORTEST: produce the least amount of digits for which the internal // identity requirement is still satisfied. If the digits are printed // (together with the correct exponent) then reading this number will give // 'v' again. The buffer will choose the representation that is closest to // 'v'. If there are two at the same distance, than the one farther away // from 0 is chosen (halfway cases - ending with 5 - are rounded up). // In this mode the 'requested_digits' parameter is ignored. // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. // - FIXED: produces digits necessary to print a given number with // 'requested_digits' digits after the decimal point. The produced digits // might be too short in which case the caller has to fill the remainder // with '0's. // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. // Halfway cases are rounded towards +/-Infinity (away from 0). The call // toFixed(0.15, 2) thus returns buffer="2", point=0. // The returned buffer may contain digits that would be truncated from the // shortest representation of the input. // - PRECISION: produces 'requested_digits' where the first digit is not '0'. // Even though the length of produced digits usually equals // 'requested_digits', the function is allowed to return fewer digits, in // which case the caller has to fill the missing digits with '0's. // Halfway cases are again rounded away from 0. // DoubleToAscii expects the given buffer to be big enough to hold all // digits and a terminating null-character. In SHORTEST-mode it expects a // buffer of at least kBase10MaximalLength + 1. In all other modes the // requested_digits parameter and the padding-zeroes limit the size of the // output. Don't forget the decimal point, the exponent character and the // terminating null-character when computing the maximal output size. // The given length is only used in debug mode to ensure the buffer is big // enough. static void DoubleToAscii(double v, DtoaMode mode, int requested_digits, char* buffer, int buffer_length, bool* sign, int* length, int* point); private: // Implementation for ToShortest and ToShortestSingle. bool ToShortestIeeeNumber(double value, StringBuilder* result_builder, DtoaMode mode) const; // If the value is a special value (NaN or Infinity) constructs the // corresponding string using the configured infinity/nan-symbol. // If either of them is NULL or the value is not special then the // function returns false. bool HandleSpecialValues(double value, StringBuilder* result_builder) const; // Constructs an exponential representation (i.e. 1.234e56). // The given exponent assumes a decimal point after the first decimal digit. void CreateExponentialRepresentation(const char* decimal_digits, int length, int exponent, StringBuilder* result_builder) const; // Creates a decimal representation (i.e 1234.5678). void CreateDecimalRepresentation(const char* decimal_digits, int length, int decimal_point, int digits_after_point, StringBuilder* result_builder) const; const int flags_; const char* const infinity_symbol_; const char* const nan_symbol_; const char exponent_character_; const int decimal_in_shortest_low_; const int decimal_in_shortest_high_; const int max_leading_padding_zeroes_in_precision_mode_; const int max_trailing_padding_zeroes_in_precision_mode_; DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter); }; class StringToDoubleConverter { public: // Enumeration for allowing octals and ignoring junk when converting // strings to numbers. enum Flags { NO_FLAGS = 0, ALLOW_HEX = 1, ALLOW_OCTALS = 2, ALLOW_TRAILING_JUNK = 4, ALLOW_LEADING_SPACES = 8, ALLOW_TRAILING_SPACES = 16, ALLOW_SPACES_AFTER_SIGN = 32 }; // Flags should be a bit-or combination of the possible Flags-enum. // - NO_FLAGS: no special flags. // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers. // Ex: StringToDouble("0x1234") -> 4660.0 // In StringToDouble("0x1234.56") the characters ".56" are trailing // junk. The result of the call is hence dependent on // the ALLOW_TRAILING_JUNK flag and/or the junk value. // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK, // the string will not be parsed as "0" followed by junk. // // - ALLOW_OCTALS: recognizes the prefix "0" for octals: // If a sequence of octal digits starts with '0', then the number is // read as octal integer. Octal numbers may only be integers. // Ex: StringToDouble("01234") -> 668.0 // StringToDouble("012349") -> 12349.0 // Not a sequence of octal // // digits. // In StringToDouble("01234.56") the characters ".56" are trailing // junk. The result of the call is hence dependent on // the ALLOW_TRAILING_JUNK flag and/or the junk value. // In StringToDouble("01234e56") the characters "e56" are trailing // junk, too. // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of // a double literal. // - ALLOW_LEADING_SPACES: skip over leading whitespace, including spaces, // new-lines, and tabs. // - ALLOW_TRAILING_SPACES: ignore trailing whitespace. // - ALLOW_SPACES_AFTER_SIGN: ignore whitespace after the sign. // Ex: StringToDouble("- 123.2") -> -123.2. // StringToDouble("+ 123.2") -> 123.2 // // empty_string_value is returned when an empty string is given as input. // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string // containing only spaces is converted to the 'empty_string_value', too. // // junk_string_value is returned when // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not // part of a double-literal) is found. // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a // double literal. // // infinity_symbol and nan_symbol are strings that are used to detect // inputs that represent infinity and NaN. They can be null, in which case // they are ignored. // The conversion routine first reads any possible signs. Then it compares the // following character of the input-string with the first character of // the infinity, and nan-symbol. If either matches, the function assumes, that // a match has been found, and expects the following input characters to match // the remaining characters of the special-value symbol. // This means that the following restrictions apply to special-value symbols: // - they must not start with signs ('+', or '-'), // - they must not have the same first character. // - they must not start with digits. // // Examples: // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK, // empty_string_value = 0.0, // junk_string_value = NaN, // infinity_symbol = "infinity", // nan_symbol = "nan": // StringToDouble("0x1234") -> 4660.0. // StringToDouble("0x1234K") -> 4660.0. // StringToDouble("") -> 0.0 // empty_string_value. // StringToDouble(" ") -> NaN // junk_string_value. // StringToDouble(" 1") -> NaN // junk_string_value. // StringToDouble("0x") -> NaN // junk_string_value. // StringToDouble("-123.45") -> -123.45. // StringToDouble("--123.45") -> NaN // junk_string_value. // StringToDouble("123e45") -> 123e45. // StringToDouble("123E45") -> 123e45. // StringToDouble("123e+45") -> 123e45. // StringToDouble("123E-45") -> 123e-45. // StringToDouble("123e") -> 123.0 // trailing junk ignored. // StringToDouble("123e-") -> 123.0 // trailing junk ignored. // StringToDouble("+NaN") -> NaN // NaN string literal. // StringToDouble("-infinity") -> -inf. // infinity literal. // StringToDouble("Infinity") -> NaN // junk_string_value. // // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES, // empty_string_value = 0.0, // junk_string_value = NaN, // infinity_symbol = NULL, // nan_symbol = NULL: // StringToDouble("0x1234") -> NaN // junk_string_value. // StringToDouble("01234") -> 668.0. // StringToDouble("") -> 0.0 // empty_string_value. // StringToDouble(" ") -> 0.0 // empty_string_value. // StringToDouble(" 1") -> 1.0 // StringToDouble("0x") -> NaN // junk_string_value. // StringToDouble("0123e45") -> NaN // junk_string_value. // StringToDouble("01239E45") -> 1239e45. // StringToDouble("-infinity") -> NaN // junk_string_value. // StringToDouble("NaN") -> NaN // junk_string_value. StringToDoubleConverter(int flags, double empty_string_value, double junk_string_value, const char* infinity_symbol, const char* nan_symbol) : flags_(flags), empty_string_value_(empty_string_value), junk_string_value_(junk_string_value), infinity_symbol_(infinity_symbol), nan_symbol_(nan_symbol) { } // Performs the conversion. // The output parameter 'processed_characters_count' is set to the number // of characters that have been processed to read the number. // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included // in the 'processed_characters_count'. Trailing junk is never included. double StringToDouble(const char* buffer, int length, int* processed_characters_count) const; // Same as StringToDouble above but for 16 bit characters. double StringToDouble(const uc16* buffer, int length, int* processed_characters_count) const; // Same as StringToDouble but reads a float. // Note that this is not equivalent to static_cast<float>(StringToDouble(...)) // due to potential double-rounding. float StringToFloat(const char* buffer, int length, int* processed_characters_count) const; // Same as StringToFloat above but for 16 bit characters. float StringToFloat(const uc16* buffer, int length, int* processed_characters_count) const; private: const int flags_; const double empty_string_value_; const double junk_string_value_; const char* const infinity_symbol_; const char* const nan_symbol_; template <class Iterator> double StringToIeee(Iterator start_pointer, int length, bool read_as_double, int* processed_characters_count) const; DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter); }; } // namespace double_conversion #endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
0
repos/ryu/third_party/double-conversion
repos/ryu/third_party/double-conversion/test/CMakeLists.txt
add_subdirectory(cctest)
0
repos/ryu/third_party/double-conversion/test
repos/ryu/third_party/double-conversion/test/cctest/gay-fixed.h
// Copyright 2006-2008 the V8 project authors. All rights reserved. // 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. #ifndef GAY_FIXED_H_ #define GAY_FIXED_H_ namespace double_conversion { struct PrecomputedFixed { double v; int number_digits; const char* representation; int decimal_point; }; // Returns precomputed values of dtoa. The strings have been generated using // Gay's dtoa in mode "fixed". Vector<const PrecomputedFixed> PrecomputedFixedRepresentations(); } // namespace double_conversion #endif // GAY_FIXED_H_
0
repos/ryu/third_party/double-conversion/test
repos/ryu/third_party/double-conversion/test/cctest/gay-shortest-single.h
// Copyright 2011, the V8 project authors. All rights reserved. // 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. #ifndef GAY_SHORTEST_SINGLE_H_ #define GAY_SHORTEST_SINGLE_H_ namespace double_conversion { struct PrecomputedShortestSingle { float v; const char* representation; int decimal_point; }; Vector<const PrecomputedShortestSingle> PrecomputedShortestSingleRepresentations(); } // namespace double_conversion #endif // GAY_SHORTEST_SINGLE_H_