- Parser에서 토큰을 트리구조로 변경하게 되며 각 언어로 프로그래밍 된 소스코드는 추상적으로 바뀌게 되고 코드의 구조는 노드로 변경하게 된다. 이러한 노드의 집합으로 만들어진 자료구조를 AST, 추상 구문 트리라 함.
- AST explorer 에서 각 Parser에 맞는 추상 구문 트리를 확인할 수 있다.
const text = "text test";
function testFunc(str) {
console.log(str)
}
testFunc(text)
- Javascript, acron 을 선택한 후 위의 예제를 입력하게 되면 아래와 같은 Tree view와 JSON view를 확인 가능하다.
{
"type": "Program",
"start": 0,
"end": 88,
"body": [
{
"type": "VariableDeclaration",
"start": 0,
"end": 25,
"declarations": [
{
"type": "VariableDeclarator",
"start": 6,
"end": 24,
"id": {
"type": "Identifier",
"start": 6,
"end": 10,
"name": "text"
},
"init": {
"type": "Literal",
"start": 13,
"end": 24,
"value": "text test",
"raw": "\"text test\""
}
}
],
"kind": "const"
},
{
"type": "FunctionDeclaration",
"start": 27,
"end": 71,
"id": {
"type": "Identifier",
"start": 36,
"end": 44,
"name": "testFunc"
},
"expression": false,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start": 45,
"end": 48,
"name": "str"
}
],
"body": {
"type": "BlockStatement",
"start": 50,
"end": 71,
"body": [
{
"type": "ExpressionStatement",
"start": 53,
"end": 69,
"expression": {
"type": "CallExpression",
"start": 53,
"end": 69,
"callee": {
"type": "MemberExpression",
"start": 53,
"end": 64,
"object": {
"type": "Identifier",
"start": 53,
"end": 60,
"name": "console"
},
"property": {
"type": "Identifier",
"start": 61,
"end": 64,
"name": "log"
},
"computed": false,
"optional": false
},
"arguments": [
{
"type": "Identifier",
"start": 65,
"end": 68,
"name": "str"
}
],
"optional": false
}
}
]
}
},
{
"type": "ExpressionStatement",
"start": 73,
"end": 87,
"expression": {
"type": "CallExpression",
"start": 73,
"end": 87,
"callee": {
"type": "Identifier",
"start": 73,
"end": 81,
"name": "testFunc"
},
"arguments": [
{
"type": "Identifier",
"start": 82,
"end": 86,
"name": "text"
}
],
"optional": false
}
}
],
"sourceType": "module"
}
- 모든 객체는 타입 이름(Program, VariableDeclaration, VariableDeclarator, Identifier 등)을 가진 노드이며, start와 end는 소스로부터의 offset이다. 결론적으로 첫줄은 text 이름의 변수를 const로 만들어서 문자열 타입의 text test 라는 값을 넣는다 라는 내용. 함수부는 testFunc 라는 식별자로 함수를 호출하며 인자로 str라는 식별자를 사용한다는 내용. AST는 이와 같이 소스 코드를 추상화된 트리 구조로 나타낸 것.
- 라이브러리인 eslint를 살펴보면 Parser로 AST를 변환하고 이를 가지고 정적 분석을 수행함.
const a = "a"
//const a = "a"
- 두 코드의 내용은 같지만 eslint로 설정하고 AST로 변환하게 되면 서로 다른 객체가 된다. 하나는 VariableDeclaaration, 하나는 CommentLine으로 변환 된다. eslint가 단순히 파일의 내용을 텍스트로 가져와서 문자열을 확인하거나 추상화 되지 않은 문자들을 가지고 분석했다면 차이를 구분하지 못했을 것. 'a' 라는 변수를 사용할 수 없다는 규칙이 있다면 일반적인 문자열 확인 방법으로는 대응하기 어렵지만 AST를 활용하면 소스 코드를 토큰으로 나눈 뒤 추상화 된 트리를 만들게 되고 소스코드에서 각 문자열이 어떤 역활을 하는지 알 수 있게 됨.
2024.09.25 - [Front-End/Javascript] - 자바스크립트 interpreter/compiler pipeline
| 객체의 전개 구문 (0) | 2024.09.25 |
|---|---|
| 배열의 전개 구문 (0) | 2024.09.25 |
| 자바스크립트 interpreter/compiler pipeline (2) | 2024.09.25 |
| 객체 구조 분해 할당 (2) | 2024.09.23 |
| 배열 구조 분해 할당 (0) | 2024.09.23 |