Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add webidl2js‑globals.js to automate install of [Exposed] globals #190

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions lib/constructs/interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,18 @@ class Interface {

const global = utils.getExtAttr(this.idl.extAttrs, "Global");
this.isGlobal = Boolean(global);
if (global && !global.rhs) {
throw new Error(`[Global] must take an identifier or an identifier list in interface ${this.name}`);
if (global) {
if (!global.rhs || (global.rhs.type !== "identifier" && global.rhs.type !== "identifier-list")) {
throw new Error(`[Global] must take an identifier or an identifier list in interface ${this.name}`);
}

if (global.rhs.type === "identifier") {
this.globalNames = new Set([global.rhs.value]);
} else {
this.globalNames = new Set(global.rhs.value.map(token => token.value));
}
} else {
this.globalNames = null;
}

const exposed = utils.getExtAttr(this.idl.extAttrs, "Exposed");
Expand Down Expand Up @@ -1193,6 +1203,27 @@ class Interface {
return obj;
};
`;

if (this.isGlobal) {
const bundleEntry = this.requires.addRelative("./webidl2js-globals.js");

this.str += `
const globalNames = ${JSON.stringify([...this.globalNames])};

/**
* Initialises the passed obj as a new global.
*
* The obj is expected to contain all the global object properties
* as specified in the ECMAScript specification.
*/
exports.setupGlobal = (obj, constructorArgs = [], privateData = {}) => {
${bundleEntry}.installInterfaces(obj, globalNames);

Object.setPrototypeOf(obj, obj[interfaceName].prototype);
obj = exports.setup(obj, obj, constructorArgs, privateData);
};
`;
}
}

addConstructor() {
Expand Down
2 changes: 2 additions & 0 deletions lib/context.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use strict";
const webidl = require("webidl2");
const Globals = require("./globals.js");
const Typedef = require("./constructs/typedef");

const builtinTypedefs = webidl.parse(`
Expand Down Expand Up @@ -38,6 +39,7 @@ class Context {
this.callbackInterfaces = new Map();
this.dictionaries = new Map();
this.enumerations = new Map();
this.globals = new Globals(this);

for (const typedef of builtinTypedefs) {
this.typedefs.set(typedef.name, new Typedef(this, typedef));
Expand Down
119 changes: 119 additions & 0 deletions lib/globals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"use strict";
const utils = require("./utils.js");

class Globals {
constructor(ctx) {
this.ctx = ctx;
this.requires = new utils.RequiresMap(ctx);

this.str = null;

this._analyzed = false;
this._constructs = null;
}

_analyzeMembers() {
const { ctx } = this;

const constructs = [];

// This is needed to ensure that the interface order is deterministic
// regardless of filesystem case sensitivity:
const ifaceNames = [...ctx.interfaces.keys(), ...ctx.callbackInterfaces.keys()].sort();

function addExtendingInterfaces(parent) {
for (const ifaceName of ifaceNames) {
const iface = ctx.interfaces.get(ifaceName);
if (iface && iface.idl.inheritance === parent.name) {
constructs.push(iface);
addExtendingInterfaces(iface);
}
}
}

for (const ifaceName of ifaceNames) {
const cb = ctx.callbackInterfaces.get(ifaceName);
if (cb) {
// Callback interface
if (cb.constants.size > 0) {
constructs.push(cb);
}
continue;
}

const iface = ctx.interfaces.get(ifaceName);
if (!iface.idl.inheritance) {
constructs.push(iface);
addExtendingInterfaces(iface);
}
}

this._constructs = constructs;
}

generate() {
this.generateInterfaces();
this.generateInstall();
this.generateRequires();
}

generateInterfaces() {
this.str += `
/**
* This object defines the mapping between the interface name and the generated interface wrapper code.
*
* Note: The mapping needs to stay as-is in order due to interface evaluation.
* We cannot "refactor" this to something less duplicative because that would break bundlers which depend
* on static analysis of require()s.
*/
exports.interfaces = {
`;

for (const { name } of this._constructs) {
this.str += `${utils.stringifyPropertyKey(name)}: require("./${name}.js"),`;
}

this.str += `
};
`;
}

generateInstall() {
this.str += `
/**
* Initializes the passed object as a new global.
*
* The object is expected to contain all the global object properties
* as specified in the ECMAScript specification.
*
* This function has to be added to the exports object
* to avoid circular dependency issues.
*/
exports.installInterfaces = (globalObject, globalNames) => {
for (const iface of Object.values(exports.interfaces)) {
iface.install(globalObject, globalNames);
}
};
`;
}

generateRequires() {
this.str = `
${this.requires.generate()}

${this.str}
`;
}

toString() {
this.str = "";
if (!this._analyzed) {
this._analyzed = true;
this._analyzeMembers();
}
this.generate();
return this.str;
}
}

module.exports = Globals;
8 changes: 8 additions & 0 deletions lib/transformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,14 @@ class Transformer {
`);
await fs.writeFile(path.join(outputDir, obj.name + ".js"), source);
}

const source = this._prettify(`
"use strict";

const utils = require("${relativeUtils}");
${this.ctx.globals.toString()}
`);
await fs.writeFile(path.join(outputDir, "webidl2js-globals.js"), source);
}

_prettify(source) {
Expand Down
6 changes: 5 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ const defaultDefinePropertyDescriptor = {
};

function toKey(type, func = "") {
if (extname(type) === ".js") {
type = type.slice(0, -3);
}

return String(func + type).replace(/[./-]+/g, " ").trim().replace(/ /g, "_");
}

Expand Down Expand Up @@ -126,7 +130,7 @@ class RequiresMap extends Map {
const key = toKey(type, func);

const path = type.startsWith(".") ? type : `./${type}`;
let req = `require("${path}.js")`;
let req = `require("${!extname(path) ? `${path}.js` : path}")`;

if (func) {
req += `.${func}`;
Expand Down
Loading