token, lexer, parser 예시 - gachi-mandoo-shell/Docs GitHub Wiki

Tokenizer

tokenization 이란 하나의 text를 여러개의 token으로 나누는 것을 의미 한다.

일반적으로는 공백, 구두점, 특수문자 등을 기준으로 나누어 지게 되는 데, 그 방법에 따라 다양한 Tokenizer가 존재 하게 된다.

Lexer

lexer의 역할은 나누어진 토큰에 대해서 의미를 분석하는 역할을 가지게 된다.

Parser

parser는 tokenizer와 lexer를 통해 분석된 Token를 가지고 구조적으로 나타낼 수 있게 해준다.

bash shell에서의 예시

ex1

bash shell에서 명령어가 들어오게 된다면 일단 token화를 시키게 된다.

echo "\"hello wolrd!\"" ; touch helloworld

이때 tokenization를 진행 하게 되면 아래와 같은 형태로 token 화 되게 된다.

[echo, "hello world!", ;, touch, helloworld]

이제 그 다음으로 lexer를 통해 의미를 부여 하게 되면 아래 와 같이 완성이 되게 된다.

[
  {
    "type": "COMMAND",
    "value": "echo"
  },
  {
    "type": "ARG",
    "value": "\"hello world!\""
  },
  {
    "type": "SPLIT",
    "value": ";"
  },
  {
    "type": "COMMAND",
    "value": "touch"
  },
  {
    "type": "ARG",
    "value": "helloworld"
  }
]

이제 이렇게 분석된 token를 가지고 parser를 통해 구조화를 진행 하게 된다.

[
  {
    "type": "EXECVE",
    "command": "echo",
    "args": ["\"hello world!\""]
  },
  {
    "type": "EXECVE",
    "command": "touch",
    "args": ["helloworld"]
  }
]

이렇게 만들어진 구조를 통해서 순서대로 실행을 하게 된다.

ex2

echo -n "This is an example" | cat -e > file1 | cat < file1 > file2

tokenization

[
  "echo",
  "-n",
  "This is an example",
  "|",
  "cat",
  "-e",
  ">",
  "file1",
  "|",
  "cat",
  "<",
  "file1",
  ">",
  "file2"
]

lexer

[
  {
    "type": "COMMAND",
    "value": "echo"
  },
  {
    "type": "ARG",
    "value": "-n"
  },
  {
    "type": "ARG",
    "value": "This is an example"
  },
  {
    "type": "PIPE",
    "value": "|"
  },
  {
    "type": "COMMAND",
    "value": "cat"
  },
  {
    "type": "ARG",
    "value": "-e"
  },
  {
    "type": "REDIRECT",
    "value": ">"
  },
  {
    "type": "FILE",
    "value": "file1"
  },
  {
    "type": "PIPE",
    "value": "|"
  },
  {
    "type": "COMMAND",
    "value": "cat"
  },
  {
    "type": "REDIRECT",
    "value": "<"
  },
  {
    "type": "FILE",
    "vlaue": "file1"
  },
  {
    "type": "REDIRECT",
    "vlaue": ">"
  },
  {
    "type": "FILE",
    "valaue": "file2"
  }
]

parser

[
  {
    "type": "PIPE",
    "first": {
      "type": "EXECVE",
      "command": "echo",
      "args": ["-n", "This is an example"]
    },
    "second": {
      "type": "PIPE",
      "first": {
        "type": "REDIRECT",
        "operator": ">",
        "command": {
          "type": "EXECVE",
          "command": "cat",
          "args": ["-e"]
        },
        "file": "file1"
      },
      "second": {
        "type": "REDIRECT",
        "operator": "<",
        "command": {
          "type": "REDIRECT",
          "operator": ">",
          "command": {
            "type": "EXECVE",
            "command": "cat",
            "args": []
          },
          "file": "file2"
        },
        "file": "file1"
      }
    }
  }
]
⚠️ **GitHub.com Fallback** ⚠️