Skip to content

Instantly share code, notes, and snippets.

@greggirwin
Created March 1, 2021 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggirwin/91dc025b1c25b9efc24996af0207bde2 to your computer and use it in GitHub Desktop.
Save greggirwin/91dc025b1c25b9efc24996af0207bde2 to your computer and use it in GitHub Desktop.
load-trap
Red []
context [
list: none
last-event: none
trap: function [
event [word!] ;-- event name
input [string! binary!] ;-- input series at current loading position
type [datatype! word! none!] ;-- type of token or value currently processed.
line [integer!] ;-- current input line number
token ;-- current token as an input slice (pair!) or a loaded value.
/extern list last-event
return: [logic!] ;-- YES: continue to next lexing stage, NO: cancel current token lexing
][
[load error] ;-- Use only events we need for faster processing
switch event [
load [append/only list token no] ;-- store loaded values ourselves
error [
last-event: reduce [event input type line token]
yes ;-- throw errors
]
]
]
set 'load-trap function [
"Load all values, returns [[values] [last-event-info]"
src [file! string! binary!] "Source file or in-memory buffer to analyze"
/extern list last-event
][
if file? src [src: read/binary src]
list: make block! 1000
either error? try [transcode/trace src :trap][
reduce [list last-event]
][
list
]
]
F_EVENT: 1
F_INPUT: 2
F_TYPE: 3
F_LINE: 4
F_TOKEN: 5
set 'show-nice-trap-info function [args [block!] "[vals event]"][
vals: args/1
event: args/2
s: event/:F_TOKEN/1
e: event/:F_TOKEN/2
print [
"So far I loaded" length? vals "values" newline
"The last of which are " mold skip tail vals -3 newline
"But I stopped parsing after" mold copy/part at head event/:F_INPUT s e - s newline
"On line" event/:F_LINE newline
"Where I thought I found a" mold event/:F_TYPE newline
"But then saw" mold event/:F_INPUT newline
]
]
]
;-- Usage example
probe load-trap "1 2 3 4a"
probe load-trap "1 2 3 [a b [c d]"
probe load-trap "[1 2 3] ]a b [c d]"
probe load-trap "[1 2 3] [a b [c d]"
probe load-trap s: {
[1 2 3]
[[4 5 6] 7 8 9] word #issue @ref
"string" <tag>
[10 11xx]
}
show-nice-trap-info load-trap s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment