blob: ac0b71e71908a5278242fc6d7afd14665f9270df [file] [log] [blame]
Johan Bay49f681a2022-01-27 09:25:13 +00001// Copyright 2021 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// @ts-check
6
7import * as fs from 'fs';
8import * as path from 'path';
9import {fileURLToPath} from 'url';
10
11/** @type {Map<string, Map<string, string[][]>>} */
12const methods = new Map();
13
14export function clearState() {
15 methods.clear();
16}
17
18export function parseTSFunction(func, node) {
19 if (!func.name.escapedText) {
20 return;
21 }
22
23 const args = func.parameters
24 .map(p => {
25 let text = p.name.escapedText;
26 if (p.questionToken) {
27 text = '?' + text;
28 }
29 if (p.dotDotDotToken) {
30 text = '...' + text;
31 }
32 return text;
33 })
34 .filter(x => x !== 'this');
35 storeMethod(node.name.text, func.name.escapedText, args);
36}
37
38/**
39 * @param {WebIDL2.IDLRootType} thing
40 * */
41export function walkRoot(thing) {
42 switch (thing.type) {
43 case 'interface':
44 walkInterface(thing);
45 break;
46 case 'interface mixin':
47 case 'namespace':
48 walkMembers(thing);
49 break;
50 }
51}
52
53/**
54 * @param {WebIDL2.InterfaceType} thing
55 * */
56function walkInterface(thing) {
57 thing.members.forEach(member => {
58 switch (member.type) {
59 case 'constructor':
60 storeMethod('Window', thing.name, member.arguments.map(argName));
61 break;
62 case 'operation':
63 handleOperation(member);
64 }
65 });
66 const namedConstructor = thing.extAttrs.find(extAttr => extAttr.name === 'NamedConstructor');
67 if (namedConstructor && namedConstructor.arguments) {
68 storeMethod('Window', namedConstructor.rhs.value, namedConstructor.arguments.map(argName));
69 }
70}
71
72/**
73 * @param {WebIDL2.NamespaceType | WebIDL2.InterfaceMixinType} thing
74 * */
75function walkMembers(thing) {
76 thing.members.forEach(member => {
77 if (member.type === 'operation') {
78 handleOperation(member);
79 }
80 });
81}
82
83/**
84 * @param {WebIDL2.OperationMemberType} member
85 * */
86function handleOperation(member) {
87 storeMethod(
88 member.special === 'static' ? (parent.name + 'Constructor') : member.parent.name, member.name,
89 member.arguments.map(argName));
90}
91
92/**
93 * @param {WebIDL2.Argument} a
94 * */
95function argName(a) {
96 let name = a.name;
97 if (a.optional) {
98 name = '?' + name;
99 }
100 if (a.variadic) {
101 name = '...' + name;
102 }
103 return name;
104}
105
106/**
107 * @param {string} parent
108 * @param {string} name
109 * @param {Array<string>} args
110 * */
111function storeMethod(parent, name, args) {
112 if (!methods.has(name)) {
113 methods.set(name, new Map());
114 }
115 const method = methods.get(name);
116 if (!method.has(parent)) {
117 method.set(parent, []);
118 }
119 method.get(parent).push(args);
120}
121
122export function postProcess(dryRun = false) {
123 for (const name of methods.keys()) {
124 // We use the set jsonParents to track the set of different signatures across parent for this function name.
125 // If all signatures are identical, we leave out the parent and emit a single NativeFunction entry without receiver.
126 const jsonParents = new Set();
127 for (const [parent, signatures] of methods.get(name)) {
128 signatures.sort((a, b) => a.length - b.length);
129 const filteredSignatures = [];
130 for (const signature of signatures) {
131 const smallerIndex = filteredSignatures.findIndex(smaller => startsTheSame(smaller, signature));
132 if (smallerIndex !== -1) {
133 filteredSignatures[smallerIndex] = (signature.map((arg, index) => {
134 const otherArg = filteredSignatures[smallerIndex][index];
135 if (otherArg) {
136 return otherArg.length > arg.length ? otherArg : arg;
137 }
138 if (arg.startsWith('?') || arg.startsWith('...')) {
139 return arg;
140 }
141 return '?' + arg;
142 }));
143 } else {
144 filteredSignatures.push(signature);
145 }
146 }
147
148 function startsTheSame(smaller, bigger) {
149 for (let i = 0; i < smaller.length; i++) {
150 const withoutQuestion = str => /[\?]?(.*)/.exec(str)[1];
151 if (withoutQuestion(smaller[i]) !== withoutQuestion(bigger[i])) {
152 return false;
153 }
154 }
155 return true;
156 }
157
158 methods.get(name).set(parent, filteredSignatures);
159 jsonParents.add(JSON.stringify(filteredSignatures));
160 }
161 // If all parents had the same signature for this name, we put a `*` as parent for this entry.
162 if (jsonParents.size === 1) {
163 methods.set(name, new Map([['*', JSON.parse(jsonParents.values().next().value)]]));
164 }
165 for (const [parent, signatures] of methods.get(name)) {
166 if (signatures.length === 1 && !signatures[0].length) {
167 methods.get(name).delete(parent);
168 }
169 }
170 if (methods.get(name).size === 0) {
171 methods.delete(name);
172 }
173 }
174 const functions = [];
175 for (const [name, method] of methods) {
176 if (method.has('*')) {
177 // All parents had the same signature so we emit an entry without receiver.
178 functions.push({name, signatures: method.get('*')});
179 } else {
180 for (const [parent, signatures] of method) {
181 if (parent.endsWith('Constructor')) {
182 functions.push(
183 {name, signatures, static: true, receiver: parent.substring(0, parent.length - 'Constructor'.length)});
184 } else {
185 functions.push({name, signatures, receiver: parent});
186 }
187 }
188 }
189 }
190 const output = `export const NativeFunctions = [\n${
191 functions
192 .map(
193 entry =>
194 ` {\n${Object.entries(entry).map(kv => ` ${kv[0]}: ${JSON.stringify(kv[1])}`).join(',\n')}\n }`)
195 .join(',\n')}\n];`;
196
197 if (dryRun) {
198 return output;
199 }
200
201 fs.writeFileSync(
202 (new URL('../../front_end/models/javascript_metadata/NativeFunctions.js', import.meta.url)).pathname,
203 `// Copyright 2020 The Chromium Authors. All rights reserved.
204// Use of this source code is governed by a BSD-style license that can be
205// found in the LICENSE file.
206// Generated from ${
207 path.relative(path.join(fileURLToPath(import.meta.url), '..', '..'), fileURLToPath(import.meta.url))}
208
209${output}
210`);
211}