Skip to content

의미 분석

의미 분석은 소스 코드가 옳은지 검사하는 과정입니다. ECMAScript 명세의 모든 "Early Error" 규칙을 확인해야 합니다.

문맥

[Yield], [Await] 같은 문법 문맥에서는 문법이 금지하면 오류를 내야 합니다:

BindingIdentifier[Yield, Await] :
  Identifier
  yield
  await

13.1.1 Static Semantics: Early Errors

BindingIdentifier[Yield, Await] : yield
* It is a Syntax Error if this production has a [Yield] parameter.

* BindingIdentifier[Yield, Await] : await
It is a Syntax Error if this production has an [Await] parameter.

따라서 다음에 오류를 내야 합니다:

javascript
async function* foo() {
  var yield, await;
}

AsyncGeneratorDeclarationAsyncGeneratorBody[+Yield], [+Await]이기 때문입니다:

AsyncGeneratorBody :
  FunctionBody[+Yield, +Await]

Biome에서 yield를 검사하는 예:

rust
// https://github.com/rome/tools/blob/5a059c0413baf1d54436ac0c149a829f0dfd1f4d/crates/rome_js_parser/src/syntax/expr.rs#L1368-L1377

pub(super) fn parse_identifier(p: &mut Parser, kind: JsSyntaxKind) -> ParsedSyntax {
    if !is_at_identifier(p) {
        return Absent;
    }

    let error = match p.cur() {
        T![yield] if p.state.in_generator() => Some(
            p.err_builder("Illegal use of `yield` as an identifier in generator function")
                .primary(p.cur_range(), ""),
        ),

스코프

선언 관련 오류:

14.2.1 Static Semantics: Early Errors

Block : { StatementList }
* It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any duplicate entries.
* It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also occurs in the VarDeclaredNames of StatementList.

스코프 트리가 필요합니다. 스코프 트리는 그 안의 varlet 선언을 담습니다. 부모를 가리키는 트리로 위로 거슬러 올라가 부모 스코프에서 바인딩 식별자를 찾습니다. indextree 크레이트를 쓸 수 있습니다.

rust
use indextree::{Arena, Node, NodeId};
use bitflags::bitflags;

pub type Scopes = Arena<Scope>;
pub type ScopeId = NodeId;

bitflags! {
    #[derive(Default)]
    pub struct ScopeFlags: u8 {
        const TOP = 1 << 0;
        const FUNCTION = 1 << 1;
        const ARROW = 1 << 2;
        const CLASS_STATIC_BLOCK = 1 << 4;
        const VAR = Self::TOP.bits | Self::FUNCTION.bits | Self::CLASS_STATIC_BLOCK.bits;
    }
}

#[derive(Debug, Clone)]
pub struct Scope {
    /// [Strict Mode Code](https://tc39.es/ecma262/#sec-strict-mode-code)
    /// [Use Strict Directive Prologue](https://tc39.es/ecma262/#sec-directive-prologues-and-the-use-strict-directive)
    pub strict_mode: bool,

    pub flags: ScopeFlags,

    /// [Lexically Declared Names](https://tc39.es/ecma262/#sec-static-semantics-lexicallydeclarednames)
    pub lexical: IndexMap<Atom, SymbolId, FxBuildHasher>,

    /// [Var Declared Names](https://tc39.es/ecma262/#sec-static-semantics-vardeclarednames)
    pub var: IndexMap<Atom, SymbolId, FxBuildHasher>,

    /// Function Declarations
    pub function: IndexMap<Atom, SymbolId, FxBuildHasher>,
}

스코프 트리는 성능상 파서 안에서 만들 수도 있고, 별도 AST 패스에서 만들 수도 있습니다.

보통 ScopeBuilder가 필요합니다:

rust
pub struct ScopeBuilder {
    scopes: Scopes,
    root_scope_id: ScopeId,
    current_scope_id: ScopeId,
}

impl ScopeBuilder {
    pub fn current_scope(&self) -> &Scope {
        self.scopes[self.current_scope_id].get()
    }

    pub fn enter_scope(&mut self, flags: ScopeFlags) {
        // Inherit strict mode for functions
        // https://tc39.es/ecma262/#sec-strict-mode-code
        let mut strict_mode = self.scopes[self.root_scope_id].get().strict_mode;
        let parent_scope = self.current_scope();
        if !strict_mode
            && parent_scope.flags.intersects(ScopeFlags::FUNCTION)
            && parent_scope.strict_mode
        {
            strict_mode = true;
        }

        let scope = Scope::new(flags, strict_mode);
        let new_scope_id = self.scopes.new_node(scope);
        self.current_scope_id.append(new_scope_id, &mut self.scopes);
        self.current_scope_id = new_scope_id;
    }

    pub fn leave_scope(&mut self) {
      self.current_scope_id = self.scopes[self.current_scope_id].parent().unwrap();
    }
}

파싱 함수 안에서 적절히 enter_scopeleave_scope를 호출합니다. 예: acorn

javascript
https://github.com/acornjs/acorn/blob/11735729c4ebe590e406f952059813f250a4cbd1/acorn/src/statement.js#L425-L437

INFO

이 방식의 단점 중 하나는 화살표 함수일 때입니다. 파싱 도중 임시 스코프를 만들었다가 나중에 화살표가 아니라 시퀀스 표현식이면 버려야 할 수 있습니다. 자세한 내용은 커버 문법을 참고하세요.

방문자 패턴

스코프 트리를 별도 패스에서 단순하게 만들려면 AST의 모든 노드를 깊이 우선 전위로 방문해야 합니다.

방문자 패턴으로 순회와 각 노드에서 할 일을 분리합니다.

방문 시 enter_scope / leave_scope를 적절히 호출해 스코프 트리를 구축합니다.