Unlimited block scopes

Unlimited block scopes

I like the idea of scopes which have the limited ability to be read-from and or written-into in order to perform secure operations

A ***blockscope*** would have this functionality

blockscope[ [params [, params]*]* ]{
    
}

let a = "a"
let a2 = "a2"
let a3 = "a3"

let b,c = blockscope[ let innerScopeA = a ]{
    a // referenceError: "a" is undefined 
    a2 // referenceError: "a2" is undefined
    a3 // referenceError: "a3" is undefined
    innerScopeA // "a" 
    let B = "B"
    let C = "C"
    return B,C
}

innerScopeA // referenceError: "innerScopeA" is undefined 
    
blockscope[ a,b,c,f = Worker("myfile.js") ]{
    innerScopeA // referenceError: "innerScopeA" is undefined 
    a // "a" 
    b // "B"
    c // "C"
    let msg = f.postMessage(a,b,c)
    let d = blockscope[]{
        let D = "D"
        blockscope[]{
            let e = "e"
            blockscope[]{
                let g = "g"
            }
        }
        return D
    }
    d // "D"
}

d // referenceError: "d" is undefined

cf. RELATED REFERENCES
SANDBOXED SCOPED FUNCTIONS - Sandboxed / Scoped function
REALMS PROPOSAL - https://github.com/tc39/proposal-realms

This can already be achieved with a mix of Proxy and with and this helper:

function blockScope(allowed = {}) {
  return new Proxy({}, {
        has: (v) => true,
        get: (_target, prop) => {
            if (prop === Symbol.unscopables) {
                return {};
            }
            if (prop in allowed) {
                return allowed[prop];
            }
            throw new ReferenceError(`${prop} is undefined`);
        }
    });
}

Example:

let a1 = "a1"
let a2 = "a2"
let a3 = "a3"

let [b,c] = (() => {with(blockScope({a1, innerScopeA2: a2})) {
    a1; // 'a1'
    a2; // referenceError: "a2" is undefined
    a3; // referenceError: "a3" is undefined
    innerScopeA2; // "a2" 
    let B = "B"
    let C = "C"
    return [B,C];
}})()

b; // 'B'
c; // 'C'
2 Likes

I see the interesting pattern with with + Proxy in many sandbox-like solutions. The main usage is to capture free variable access. What if we provide a modern syntax for this task?