From 4e71c83942a68c561cb5624174ae37650027d728 Mon Sep 17 00:00:00 2001 From: Aleteoryx Date: Tue, 16 Sep 2025 23:15:58 -0400 Subject: [PATCH] grep's -o flag --- grep.tal | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/grep.tal b/grep.tal index 4536dca5a054bb58245f39d5eb3fecd293eac40d..00b070fa14262f1b7a1e48eeabdce3d520636cef 100644 --- a/grep.tal +++ b/grep.tal @@ -7,7 +7,7 @@ %dbg { #010e DEO } %kil { #010f DEO BRK } -%p2brk { POP2r BRK } +%p2brk { BRK } ( replace this with POP2r BRK when debugging ) ( --- initialization --- ) @@ -69,7 +69,9 @@ DEIk LIT "P NEQ ?{ POP ( [P]attern mode ) ;lut/in-pattern ;lut/parser-jmp STA2 BRK } - DEIk LIT "o NEQ ?{ POP BRK } + DEIk LIT "o NEQ ?{ POP ( [o]nly print matches ) + #01 ;bitap/only-flag STA + BRK } DEI ,unknopt/opt STR !unknopt @@ -106,17 +108,20 @@ ( shift-or ) #10 SFT2 ( SHIFT in a 0 ) lut/get-addr LDA2 ORA2 ( OR with LUT value ) - + ( matches are stored in the high bit of the top byte of the return stack. if the high bit is low [i.e. we got a match], - this will set match to 00, otherwise it will stay 01. ) + this will set match to 00, otherwise it will stay 80. ) DUP2 [ LIT &sft $1 ] SFT2 - POP STH ANDr BRK + POP STH ANDr + [ LIT &only-flag 00 ] ?/do-only + BRK @bitap/newline ( state* `match -> state* `match ) ;/line ,/ptr STR2 ( reset line ptr ) POP2 #ffff ( reset state ) STHr [ LITr 80 ] ( reset match ) + ,/only-flag LDR ORA ( only mode? ) ?{ ( we saw a match, print the line ) ;/line &loop @@ -126,6 +131,21 @@ POP2 } BRK +@bitap/do-only ( `match -- `match ) + STHrk ?{ + POPr [ LITr 80 ] ( reset flag ) + ,/ptr LDR2 DUP2 ( offset into line ) + ;lut/len LDA2 ( get length to print ) + #04 SFT ( get actual length ) + SUB2 SWP2 ( start* end* ) + #0a ROT ROT STA ( write a newline ) + &only-loop + LDAk DUP #18 DEO + STH INC2 STHr + #0a NEQ ?/only-loop + POP2 + } BRK + ( --- look-up table generation & pattern parsing --- ) @@ -221,7 +241,7 @@ DUP2 STH2rk LDA2 AND2 STH2rk STA2 INC2r INC2r - NEQ2rk dbg STHr ?/range-loop + NEQ2rk STHr ?/range-loop POP2r POP2r POP2 ;/in-class ;/parser-jmp STA2 p2brk