Advertisement
Tkap1

Untitled

Jan 20th, 2024
810
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. const TOKEN_NUMBER = 0
  4. const TOKEN_IDENTIFIER = 1
  5.  
  6. function main()
  7. {
  8.     // USAGE
  9.     // USAGE
  10.     // USAGE
  11.     const input = "hello adrian 123";
  12.     let tokenizer = {text: input, index: 0};
  13.  
  14.     const token = get_token(tokenizer); // returns type = identifier, text = "hello"
  15.     token = get_token(tokenizer); // returns type = identifier, text = "adrian"
  16.     token = get_token(tokenizer); // returns type = number, text = "123"
  17.  
  18.     // If you want to look at the next token but not advance the tokenizer:
  19.     token = get_token({...tokenizer})
  20.  
  21.     return 0;
  22. }
  23.  
  24. function get_token(tokenizer)
  25. {
  26.     let token = {type: null, text: null};
  27.     eat_whitespace(tokenizer);
  28.     if(is_number(tokenizer.text[tokenizer.index])) {
  29.         token.type = TOKEN_NUMBER;
  30.         let len = 0;
  31.         while(is_number(tokenizer.text[tokenizer.index])) {
  32.             len += 1;
  33.         }
  34.         token.text = tokenizer.text.substring(tokenizer.index, tokenizer.index + len);
  35.         tokenizer.index += len;
  36.     }
  37.     else if(...) { // logic for an identifier
  38.  
  39.     }
  40.     else if(...) { // logic for something else
  41.  
  42.     }
  43.     // ...
  44.     else {
  45.         printf("We do not understand the input!\n");
  46.     }
  47.     return token;
  48. }
  49.  
  50. function eat_whitespace(tokenizer)
  51. {
  52.     while(
  53.         tokenizer.text[tokenizer.index] == ' ' || tokenizer.text[tokenizer.index] == '\n' || tokenizer.text[tokenizer.index] == '\t' ||
  54.         tokenizer.text[tokenizer.index] == '\r'
  55.     ) {
  56.         tokenizer.index += 1;
  57.     }
  58. }
  59.  
  60. function is_number(char)
  61. {
  62.     return char >= '0' && char <= '9';
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement