// ───────────────────────────────────────────────────────────────────────────── // INTERPRETER [Behavioral] // ───────────────────────────────────────────────────────────────────────────── // FIRST VISIT : From Session 2.2, read the two tables in section 0 and stop. Run its code after Session 3.4; // sections 1 and 2 are Unit 9. // INTENT : Given a language, define a representation for its grammar along with an interpreter that uses // the representation to interpret sentences in the language. // PROBLEM : Ops/users need to express rules ("price * qty - discount / 2", "tier == gold and region in EU") // as DATA, not code — you need a tiny language, a tree for it, and an evaluator over a context. // SAY : Participants: AbstractExpression (interpret(context)), TerminalExpression (literal, variable), // NonterminalExpression (add, mul, and, or — holds sub-expressions), Context (variable values), // Client (parses/builds the tree). Pitch: "grammar rules become node classes; evaluating is // walking the tree." // SEEN IN : `RegExp`; template engines (Handlebars/Mustache, JSX → createElement); MongoDB / Prisma `where` // query objects; GraphQL-js & SQL parsers; rules engines & feature flags (JSON Logic, LaunchDarkly // targeting); `JSON.parse`, math.js; CSS selector matching in `querySelector`. // VS : Visitor separates operations from the tree (add ops without touching nodes); Interpreter puts ONE // operation (interpret) on every node. Composite is the structure; Interpreter is a Composite whose // job is evaluating a language. Strategy picks an algorithm; Interpreter runs a sentence. // ───────────────────────────────────────────────────────────────────────────── 'use strict'; const assert = require('node:assert/strict'); // ── 0. Why this page is linked from CSS: nav a:hover // Session 2.2 wrote `nav a:hover`. A selector is a tiny language. The browser splits it into pieces, // builds a tree from them, and asks each element on the page "do you match?". That is the whole pattern. // // The four pieces of `nav a:hover` (the space is one of them), and the question each piece asks an element: // // piece kind question asked of the element // nav type is your tag nav? // (space) descendant is there an element above you that answers yes to the piece on the left? // a type is your tag a? // :hover pseudo-class is the pointer over you right now? // // Three elements, asked in turn. One "no" anywhere means the rule does not apply: // // element nav above? tag a? hovered? matches // an inside