lava 0.4.9

Rust wrapper to manipulate Vulkan more conveniently than with bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
const path = require('path');
const fs = require('fs');
const XML = require('pixl-xml')
const { EXTENSIONS } = require('./data');

const DOWNLOAD_DIR_PATH = path.join(__dirname, '..', 'download');
const VULKAN_CORE_H_PATH = path.join(DOWNLOAD_DIR_PATH, `vulkan_core.h`);
const VK_XML_PATH = path.join(DOWNLOAD_DIR_PATH, `vk.xml`);

let VULKAN_H = null;
let VK_XML_STR = null;
let VK_XML = null;
let ENUMS = null;
let BIT_FLAGS = null;
let STRUCTS = null;
let HANDLES = null;
let FUNCTIONS = null;
let EXTENSION_NAMES = null;
let TYPEDEFS = null;
let BOOTSTRAP_DONE = false;

function bootstrap() {
    if (!BOOTSTRAP_DONE) {
        VULKAN_H = fs.readFileSync(VULKAN_CORE_H_PATH, 'utf8');
        VK_XML_STR = fs.readFileSync(VK_XML_PATH, 'utf8').replace(/->/g, '::');
        VK_XML = XML.parse(VK_XML_STR);
        ENUMS = parseEnums();
        BIT_FLAGS = parseBitFlags();
        STRUCTS = parseStructs();
        HANDLES = parseHandles();
        FUNCTIONS = parseFunctions();
        EXTENSION_NAMES = parseExtensionNames();
        TYPEDEFS = parseTypedefs();
        BOOTSTRAP_DONE = true;
    }
}

function getByName(obj, typeName) {
    const { name, extension } = parseName(typeName);

    return obj[extension][name];
}

function getAll(obj) {
    bootstrap();
    return Object.values(obj).reduce((acc, subObj) => acc.concat(Object.values(subObj)), []);
}

function get(obj, type) {
    return (obj[type.extension] || {})[type.typeName];
}

function isAllowedFunction(func) {
    return true;

    const allowedExtensions = ['EXT', 'KHR'];
    const hasExtension = /[A-Z]{2}$/.test(func.name);

    return !hasExtension || allowedExtensions.some(ext => func.name.endsWith(ext));
}

function getAllEnums() { return getAll(ENUMS); }
function getAllBitFlags() { return getAll(BIT_FLAGS); }
function getAllStructs() { return getAll(STRUCTS); }
function getAllHandles() { return getAll(HANDLES); }
function getAllFunctions() { bootstrap(); return FUNCTIONS.slice().filter(isAllowedFunction); }
function getAllExtensionNames() { bootstrap(); return EXTENSION_NAMES.slice(); }
function getAllTypedefs() { bootstrap(); return TYPEDEFS.slice(); }

function getEnumByName(name) { return getByName(ENUMS, name); }
function getBitFlagsByName(name) { return getByName(BIT_FLAGS, name); }
function getStructByName(name) { return getByName(STRUCTS, name); }
function getHandleByName(name) { return getByName(HANDLES, name); }

function getEnum(type) { return get(ENUMS, type); }
function getBitFlags(type) { return get(BIT_FLAGS, type); }
function getStruct(type) { return get(STRUCTS, type); }
function getHandle(type) { return get(HANDLES, type); }

function isHandle(name) { return !!getByName(HANDLES, name); }

function parseName(str) {
    let extension = '';

    for (let ext of EXTENSIONS) {
        if (str.endsWith(ext)) {
            extension = ext.toLowerCase();
        }
    }

    return {
        extension: extension,
        name: str.substring(0, str.length - extension.length)
    };
}

function listToObj(array) {
    const types = {};

    array.forEach(type => {
        const byExtension = types[type.extension] || (types[type.extension] = {});
        byExtension[type.name] = type;
    });

    return types;
}

function parseField(str) {
    const match = str.match(/\s*([\w* ]+)\s+(\w+)(?:\[(\w+)\])?(?:\[(\w+)\])?(:\d+)?\s*;?\s*$/);

    if (!match) {
        return null;
    }

    const fullType = match[1].replace('FlagBits', 'Flags').replace(' struct ', ' ').trim();
    const name = match[2].trim();
    const fieldName = fullType.replace(/\*\*$/, '').replace(/ const\*$/, '').replace(/(?:const )?(\w+)\*?/, '$1');
    const fieldTypeNameInfo = parseName(fieldName);
    const typeName = fieldTypeNameInfo.name;
    const extension = fieldTypeNameInfo.extension;
    const isPointer = fullType.endsWith('*');
    const isDoublePointer = fullType.endsWith(' const*') || fullType.endsWith('**');
    const isConst = fullType.startsWith('const ');
    const arraySizeIdentifier1 = match[3];
    const arraySizeIdentifier2 = match[4];
    const arraySize1 = parseConstant(arraySizeIdentifier1);
    const arraySize2 = parseConstant(arraySizeIdentifier2);
    const countFor = [];

    let arraySize = null;

    if (arraySize1) {
        if (!arraySize2) {
            arraySize = arraySize1;
        } else {
            arraySize = arraySize1 * arraySize2;
        }
    }

    // TODO: take the `bits` into account in strict fields such as `int value:8;`

    return { name, extension, fullType, typeName, isPointer, isDoublePointer, isConst, arraySize, countFor };
}

function parseExtensionNames() {
    const regexp = /#define \w+\s+"\w+"/g;
    const match = VULKAN_H.match(regexp);

    const extensionNames = match.map(str => {
        const [_, name, value] = str.split(/\s+/)

        return { name, value };
    });

    return extensionNames;
}

function parseTypedefs() {
    const regexp = /typedef\s+\w+\s+\w+;/g;
    const match = VULKAN_H.match(regexp);

    return match.map(str => {
        const [_, baseType, newType] = str.substring(0, str.indexOf(';')).split(/\s+/);

        if (baseType.startsWith('uint') || baseType === 'VkFlags' || baseType.endsWith('FlagBits')) {
            return null;
        }

        return {
            baseType: parseName(baseType),
            newType: parseName(newType)
        };
    }).filter(x => x);
}

function parseEnums() {
    const regexp = /typedef enum \w+ {\n([^}]+)\n}/gmi;
    const match = VULKAN_H.match(regexp);

    const enums = match.map(str => {
        const structName = str.split(' ', 3)[2];
        const structNameInfo = parseName(structName);
        const name = structNameInfo.name;
        const extension = structNameInfo.extension;
        const fieldsStr = str.substring(str.indexOf('{') + 2, str.indexOf('}') - 1);

        if (name.endsWith('FlagBits')) {
            return null;
        }

        const fields = fieldsStr.split('\n').map(line => {
            const match = line.match(/^\s*([0-9A-Z_]+)\s*=\s*(-?(?:0x)?\d+),?$/);

            if (!match) {
                return null;
            }

            return {
                name: match[1].trim(),
                value: match[2].trim()
            };
        }).filter(x => x);

        return { name, extension, fields };
    }).filter(x => x);

    return listToObj(enums);
}

function parseBitFlags() {
    const defined = {};
    const flagBitsRegexp = /typedef enum \w+FlagBits[A-Z]* {\n([^}]+)\n}/gmi;
    const match = VULKAN_H.match(flagBitsRegexp);

    match.forEach(str => {
        const name = str.split(' ', 3)[2];
        const fieldsStr = str.substring(str.indexOf('{') + 2, str.indexOf('}') - 1);

        const fields = fieldsStr.split('\n').map(line => {
            const match = line.match(/^\s*([0-9A-Z_]+)\s*=\s*(0x[\dA-F]{8})|([A-Z_]+)|(0),?\s*$/);

            if (!match) {
                throw new Error(`for enum ${name}: unexpected field "${line}"`);
            }

            return {
                name: match[1],
                value: match[2] || match[3] || match[4]
            };
        }).filter(({value}) => value !== '0x7FFFFFFF' && value.startsWith('0x'));

        defined[name] = fields;
    });

    const flagsRegexp = /typedef VkFlags \w+;/g
    const match2 = VULKAN_H.match(flagsRegexp);

    const bitFlags = match2.map(str => {
        const fullName = str.substring(str.lastIndexOf(' ') + 1, str.indexOf(';'));
        const flagBitsName = fullName.replace('Flags', 'FlagBits');
        const nameInfo = parseName(fullName);
        const fields = defined[flagBitsName] || [];

        return {
            name: nameInfo.name,
            extension: nameInfo.extension,
            fields: fields
        };
    });

    return listToObj(bitFlags);
}

function parseHandles() {
    const regexp = /(VK_DEFINE_HANDLE|VK_DEFINE_NON_DISPATCHABLE_HANDLE)\(\w+\)\n/gm;
    const match = VULKAN_H.match(regexp);

    const handles = match.map(line => {
        const handleName = line.substring(line.indexOf('(') + 1, line.indexOf(')'));
        const nameInfo = parseName(handleName);

        return {
            name: nameInfo.name,
            extension: nameInfo.extension
        };
    });

    return listToObj(handles);
}

function parseConstant(name) {
    if (!name) {
        return null;
    }

    if (!isNaN(+name)) {
        return name;
    }

    const match = VULKAN_H.match(new RegExp(`#define\\s+${name}\\s+([0-9.]+)`));

    if (!match) {
        throw new Error(`cannot find constant ${name}`);
    }

    return match[1];
}

function parseStructs() {
    const regexp = /typedef struct \w+ {\n([^}]+)\n}/gmi;
    const match = VULKAN_H.match(regexp);

    const structs = match.map(str => {
        const structName = str.split(' ', 3)[2];
        const structNameInfo = parseName(structName);
        const name = structNameInfo.name;
        const extension = structNameInfo.extension;
        const fieldsStr = str.substring(str.indexOf('{') + 2, str.indexOf('}') - 1);

        const xmlDef = VK_XML.types.type.find(def => def.name === structName);

        if (!Array.isArray(xmlDef.member)) {
            xmlDef.member = [xmlDef.member];
        }

        const fields = fieldsStr.split('\n').filter(x => x).map(line => {
            const fieldInfo = parseField(line);

            if (!fieldInfo) {
                throw new Error(`unexpected line for struct ${structName}: "${line}"`);
            }

            return fieldInfo;
        });

        let lastField = null;
        for (let field of fields) {
            const xmlMember = xmlDef.member.find(member => member.name === field.name);

            field.values = xmlMember.values;

            if (xmlMember.name === 'pCode') {
                xmlMember.len = "codeSize";
            }

            field.isOptional = !!xmlMember.optional;
            field.countField = (xmlMember.len || '').split(',').find(str => fields.some(field => field.name === str));

            if (areCountAndArray(lastField, field)) {
                field.countField = lastField.name;
            }

            lastField = field;
        }

        for (let field of fields) {
            if (structName !== 'VkDescriptorSetLayoutBinding' || field.name !== 'descriptorCount') {
                field.countFor = fields.filter(otherField => otherField.countField === field.name).map(f => f.name);
            }
        }

        return { name, extension, fields };
    });

    return listToObj(structs);
}

function areCountAndArray(field1, field2) {
    return field1 && field2 &&
    (
        (
            (field1.name === 'dataSize' || field1.name === 'pDataSize') &&
            field2.name === 'pData'
        )
    ||
        (
            field1.name.startsWith(field2.name.substring(0, field2.name.length - 1)) &&
            field1.name.endsWith('Count') &&
            field1.fullType === 'uint32_t'
        )
    );
}

function parseFunctions() {
    const regexp = /(?:VKAPI_ATTR\s+)?(VkResult|void)\s+(?:VKAPI_CALL\s+)?(\w+)\s*\(([^;]+)\)/gm;
    const match = VULKAN_H.match(regexp);

    const functions = match.map(str => {
        const words = str.replace(/VKAPI_ATTR|VKAPI_CALL/g, '').trim().split(/\W+/, 2);
        const type = words[0];
        const name = words[1];

        const args = str.substring(str.indexOf('(') + 1, str.indexOf(')')).split(',').map(x => x.trim()).map(argStr => {
            const argInfo = parseField(argStr);

            if (!argInfo) {
                throw new Error(`unexpected arg "${argStr}" for function "${name}"`);
            }

            return argInfo;
        });

        let xml = VK_XML.commands.command.find(c => (c.proto && c.proto.name === name) || c.name === name);
        let successCodes = null;
        let errorCodes = null;
        
        if (xml) {
            if (xml.alias) {
                return null;
                xml = VK_XML.commands.command.find(c => c.proto && c.proto.name === xml.alias)
            }
    
            successCodes = (xml.successcodes ? xml.successcodes.split(',') : []);
            errorCodes = (xml.errorcodes ? xml.errorcodes.split(',') : []);

            const xmlParams = Array.isArray(xml.param) ? xml.param : [xml.param];
    
            if (!xmlParams) {
                throw new Error(`function ${name} does not have a xml`)
            }

            let lastArg = null;
            for (let arg of args) {
                const xmlParam = xmlParams.find(p => p.name === arg.name);
    
                if (!xmlParam) {
                    throw new Error(`function "${name}": missing xml parameter ${arg.name}`);
                }
    
                arg.values = xmlParam.values;
    
                arg.isOptional = !!xmlParam.optional;
                // if (arg.typeName !== 'void') {
                    arg.countField = (xmlParam.len || '').split(',').find(str => args.some(arg => arg.name === str || str.startsWith(`${arg.name}::`)));
    
                    if (areCountAndArray(lastArg, arg)) {
                        arg.countField = lastArg.name;
                    }
                // }
    
                lastArg = arg;
            }
    
            for (let arg of args) {
                arg.countFor = args.filter(otherArg => otherArg.countField === arg.name).map(a => a.name);
            }
        }

        return { name, type, args, successCodes, errorCodes };
    }).filter(f => f);

    return functions;
}

function getExtensions() {
    return EXTENSIONS.slice();
}

module.exports = {
    getAllEnums,
    getAllBitFlags,
    getAllStructs,
    getAllHandles,
    getAllFunctions,
    getAllExtensionNames,
    getAllTypedefs,
    getEnumByName,
    getBitFlagsByName,
    getStructByName,
    getHandleByName,
    getEnum,
    getBitFlags,
    getStruct,
    getHandle,
    isHandle,
    getExtensions
};