1- use super :: tokenizer:: { Token , Tokenkind } ;
1+ use crate :: lexericals :: tokenizer:: { Token , Tokenkind } ;
22
33#[ derive( Debug ) ]
44pub struct Lexer {
@@ -45,14 +45,31 @@ impl Lexer {
4545 ';' => Token :: new ( Tokenkind :: Semicolon , self . ch . to_string ( ) ) ,
4646 '\0' => Token :: new ( Tokenkind :: Eof , String :: new ( ) ) , // End of file token
4747
48- _ => Token :: new ( Tokenkind :: Illegal , self . ch . to_string ( ) ) ,
49-
48+ _ => return if Lexer :: is_letter ( self . ch ) {
49+ let literal = self . read_identifier ( ) ;
50+ let kind = Tokenkind :: lookup_ident ( & literal) ;
51+ Token :: new ( kind, literal)
52+ } else {
53+ Token :: new ( Tokenkind :: Illegal , self . ch . to_string ( ) )
54+ } ,
5055
5156
5257 } ;
5358 self . read_token ( ) ; // Move to the next character
5459 token
5560 }
61+ fn is_letter ( ch : char ) -> bool {
62+ ch. is_alphabetic ( ) || ch == '_'
63+ }
64+
65+ fn read_identifier ( & mut self ) -> String {
66+ let mut literal = String :: new ( ) ;
67+ while Lexer :: is_letter ( self . ch ) {
68+ literal. push ( self . ch ) ;
69+ self . read_token ( ) ;
70+ }
71+ literal
72+ }
5673
5774
5875}
@@ -62,7 +79,14 @@ mod test {
6279 use super :: * ;
6380 #[ test]
6481 fn read_token ( ) {
65- let input ="=+(){},;" ;
82+ let input =r#"let five = 5;
83+ let ten = 10;
84+ let add = fn(x, y) {
85+ x + y;
86+ };
87+ let result = add(five, ten);
88+ "# ;
89+
6690 let expect_token = vec ! [
6791 Token :: new ( Tokenkind :: Assign , String :: from( "=" ) ) ,
6892 Token :: new ( Tokenkind :: Plus , String :: from( "+" ) ) ,
0 commit comments