Skip to content

Instantly share code, notes, and snippets.

@Klafyvel
Created October 14, 2022 17:25
Show Gist options
  • Save Klafyvel/8db73a6a3169b2b08fa92a191031a991 to your computer and use it in GitHub Desktop.
Save Klafyvel/8db73a6a3169b2b08fa92a191031a991 to your computer and use it in GitHub Desktop.
module Mockup
abstract type TokenType end
struct AToken <: TokenType end
struct BToken <: TokenType end
struct Token{T <: TokenType}
position::Int
value::Char
end
scan(c::Char, input) = first(input) == c
scan(::AToken, input) = scan('A', input)
scan(::BToken, input) = scan('B', input)
const REGISTERED_TOKENTYPES = [AToken(), BToken()]
function scan(input; charnum=0)
success = false
tokentype = nothing
for scanner in REGISTERED_TOKENTYPES
success = scan(scanner, input)
if success
tokentype = scanner
break
end
end
if !success
error("No suitable token found for input at char $charnum")
end
Token{typeof(tokentype)}(charnum, first(input))
end
tokenize(input) = Token[scan(c, charnum=i) for (i,c) in enumerate(input)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment