// compare declarations from the compiler AST, independently of implementation bodies. module main import nspkg.tests.tooling import json2 import os type Surface = map[string]map[string]json2.Any fn main() { run() or { eprintln(err) exit(1) } } fn field(node map[string]json2.Any, key string) json2.Any { return node[key] or { json2.Any(json2.null) } } fn normalized(value json2.Any) json2.Any { match value { map[string]json2.Any { mut result := map[string]json2.Any{} for key, item in value { if key != 'pos' { result[key] = normalized(item) } } return result } []json2.Any { return value.map(normalized(it)) } string { mut result := '' mut index := 0 for index < value.len { if value[index..].starts_with('nspkg.') && (index == 0 || !(value[index - 1].is_alnum() || value[index - 1] == `_`)) { index += 'nspkg.'.len } else { result += value[index].ascii_str() index++ } } return result } else { return value } } } // object key order is immaterial, while declaration and field array order is API. fn canonical(value json2.Any) string { match value { map[string]json2.Any { mut keys := value.keys() keys.sort() return '{' + keys.map(json2.encode(it) + ':' + canonical(field(value, it))).join(',') + '}' } []json2.Any { return '[' + value.map(canonical(it)).join(',') + ']' } else { return json2.encode(value) } } } fn surface(compiler string) !Surface { mut result := Surface(map[string]map[string]json2.Any{}) for section in ['functions', 'records', 'enums', 'constants', 'types'] { result[section] = map[string]json2.Any{} } mut aliases := map[string]json2.Any{} mut files := os.ls(@VMODROOT)! files.sort() for path in files { if !path.ends_with('.v') || path.ends_with('_test.v') { continue } parsed := json2.parse(tooling.command(compiler, ['ast', '-p', '-s', os.join_path(@VMODROOT, path)])!)!.as_map() for file in field(parsed, 'files').as_array() { for value in field(file.as_map(), 'children').as_array() { node := value.as_map() kind := field(node, 'kind').str() name := field(node, 'value').str() if kind == 'type_decl' { aliases[name] = normalized(node['type'] or { json2.Any('') }) } // the compiler marks public declarations with the arrow token. if field(node, 'op').str() != 'arrow' { continue } children := field(node, 'children').as_array() match kind { 'fn_decl' { mut parameters := []json2.Any{} for child in children { item := child.as_map() if field(item, 'kind').str() != 'param' { continue } parameters << json2.Any({ 'type': normalized(field(item, 'type')) 'mutable': json2.Any(field(item, 'is_mut').bool()) 'receiver': json2.Any(field(item, 'op').str() == 'dot') }) } result['functions'][name] = json2.Any({ 'returns': normalized(node['type'] or { json2.Any('') }) 'parameters': json2.Any(parameters) }) } 'struct_decl', 'enum_decl' { child_kind := if kind == 'struct_decl' { 'field_decl' } else { 'enum_field' } fields := children.filter(field(it.as_map(), 'kind').str() == child_kind).map(normalized(it)) section := if kind == 'struct_decl' { 'records' } else { 'enums' } result[section][name] = json2.Any({ 'kind': node['type'] or { json2.Any(if kind == 'struct_decl' { 'struct' } else { 'enum' }) } 'fields': json2.Any(fields) }) } 'const_decl' { for child in children { item := child.as_map() if field(item, 'kind').str() == 'const_field' { result['constants'][field(item, 'value').str()] = normalized(item['children'] or { json2.Any([]json2.Any{}) }) } } } 'type_decl' { result['types'][name] = normalized(node['type'] or { json2.Any('') }) } else {} } } } } for { mut words := map[string]bool{} mut word := '' for byte in json2.encode(result).bytes() { if byte.is_alnum() || byte == `_` { word += byte.ascii_str() } else if word != '' { words[word] = true word = '' } } if word != '' { words[word] = true } mut added := false for name, value in aliases { if name in words && name !in result['types'] { result['types'][name] = value added = true } } if !added { break } } return result } fn differences(expected Surface, actual Surface) []string { mut errors := []string{} for section, entries in expected { for name, value in entries { found := actual[section][name] or { errors << 'missing ${section}: ${name}' continue } if section in ['records', 'enums'] { want := value.as_map() got := found.as_map() want_fields := field(want, 'fields').as_array() got_fields := field(got, 'fields').as_array() if canonical(field(got, 'kind')) != canonical(field(want, 'kind')) || got_fields.len < want_fields.len || canonical(json2.Any(got_fields[..want_fields.len])) != canonical(json2.Any(want_fields)) { errors << 'changed ${section}: ${name}' } } else if canonical(found) != canonical(value) { errors << 'changed ${section}: ${name}' } } } return errors } fn replace_at(value json2.Any, path []string, replacement json2.Any) json2.Any { if path.len == 0 { return normalized(replacement) } match value { map[string]json2.Any { mut changed := map[string]json2.Any{} for key, item in value { changed[key] = normalized(item) } changed[path[0]] = replace_at(field(value, path[0]), path[1..], replacement) return changed } []json2.Any { mut changed := value.clone() index := path[0].int() changed[index] = replace_at(value[index], path[1..], replacement) return changed } else { panic('invalid verifier self-test path') } } } fn self_test(expected Surface) ! { mut removed := json2.decode[Surface](json2.encode(expected))! removed['functions'].delete('Handle.trans_commit') assert differences(expected, removed).len > 0 for path, replacement in { 'functions/Handle.pkg_load/returns': json2.Any('?&Package') 'functions/List.pkgs/parameters/0/mutable': json2.Any(false) 'enums/SigLevel/fields/0/children/0/value': json2.Any('1') } { changed := json2.decode[Surface](json2.encode(replace_at(json2.decode[json2.Any](json2.encode(expected))!, path.split('/'), replacement)))! assert differences(expected, changed).len > 0 } fields := field(field(expected['records'], 'File').as_map(), 'fields').as_array() shortened := replace_at(json2.decode[json2.Any](json2.encode(expected))!, [ 'records', 'File', 'fields', ], json2.Any(fields[..fields.len - 1])) assert differences(expected, json2.decode[Surface](json2.encode(shortened))!).len > 0 mut extended := field(field(expected['records'], 'Handle').as_map(), 'fields').as_array().clone() extended << json2.Any({ 'kind': json2.Any('field_decl') 'value': json2.Any('backend') 'type': json2.Any('voidptr') }) addition := replace_at(json2.decode[json2.Any](json2.encode(expected))!, ['records', 'Handle', 'fields'], json2.Any(extended)) assert differences(expected, json2.decode[Surface](json2.encode(addition))!).len == 0 } fn run() ! { args := tooling.options(false)! actual := surface(args.compiler)! baseline := os.join_path(@VMODROOT, 'tests', 'api_surface.json') if args.record { os.write_file(baseline, json2.encode(actual, prettify: true) + '\n')! } expected := json2.decode[Surface](os.read_file(baseline)!)! if args.self_test { self_test(expected)! } errors := differences(expected, actual) if errors.len > 0 { return error('Public V API changed:\n' + errors.join('\n')) } println('Public V API preserved: ${expected['functions'].len} functions, ${expected['records'].len} records, ${expected['enums'].len} enums') }