#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-
#
# Advisory plugin-type descriptor linter.

%modern
%requires reflection

const KnownHelperAbis = {
    "UnaryValue": True,
    "BinaryValue": True,
    "CallValueList": True,
    "SubscriptValue": True,
    "Construct": True,
    "DenseBufferUnary": True,
    "DenseBufferBinary": True,
};

sub usage(int rc) {
    string text = sprintf("Usage: %s [--module-name NAME] <module-name-or-qmod-path>\n\n"
        "Loads a plugin module, reads its committed PluginRegistry descriptors, and\n"
        "reports descriptor errors and advisory warnings. Use --module-name when the\n"
        "module reference is a path or when loading registers more than one module.\n\n"
        "Options:\n"
        "  --require-runtime-symbols  Fail when an operation has no runtime helper symbol.\n"
        "  --require-llvm             Fail when any operation has no accepted LLVM codegen hook.\n"
        "  --require-llvm=OP[,OP...]  Fail when matching operation names have no accepted LLVM hook.\n"
        "  --warnings-are-errors      Treat advisory warnings as errors.\n",
        get_script_name());
    if (rc) {
        stderr.printf("%s", text);
    } else {
        printf("%s", text);
    }
    exit(rc);
}

*string module_name;
*string module_ref;
bool require_runtime_symbols = False;
bool require_all_llvm = False;
bool warnings_are_errors = False;
hash<auto> required_llvm_ops = {};

while (ARGV.size()) {
    string arg = shift ARGV;
    if (arg == "-h" || arg == "--help") {
        usage(0);
    } else if (arg == "--module-name") {
        if (!ARGV.size()) {
            stderr.printf("ERROR: --module-name requires a value\n");
            usage(2);
        }
        module_name = shift ARGV;
    } else if (arg =~ /^--module-name=(.*)$/) {
        module_name = $1;
    } else if (arg == "--require-runtime-symbols") {
        require_runtime_symbols = True;
    } else if (arg == "--require-llvm") {
        require_all_llvm = True;
    } else if (arg =~ /^--require-llvm=/) {
        string llvm_list = arg.substr(15);
        foreach string name in (llvm_list.split(",")) {
            if (name) {
                required_llvm_ops{name} = True;
            }
        }
    } else if (arg == "--warnings-are-errors") {
        warnings_are_errors = True;
    } else if (!exists module_ref) {
        module_ref = arg;
    } else {
        stderr.printf("ERROR: unexpected argument: %s\n", arg);
        usage(2);
    }
}

if (!exists module_ref) {
    usage(2);
}
bool module_ref_is_path = module_ref =~ /[\/\\]/;
string load_ref = module_ref;
if (module_ref_is_path && !absolute_path(module_ref)) {
    load_ref = getcwd() + "/" + module_ref;
}

PluginRegistry registry = PluginRegistry::getProcessRegistry();
hash<auto> before = {};
foreach string name in (registry.getProcessModules()) {
    before{name} = True;
}

try {
    if (module_ref_is_path && exists module_name) {
        Program loader(PO_NEW_STYLE);
        loader.parse(sprintf("%%prepend-module-path %y\n%%requires %s\nsub __qore_plugin_lint_loader() {}\n",
            dirname(load_ref), module_name), "qore-plugin-lint module loader");
    } else {
        load_module(load_ref);
    }
} catch (hash<ExceptionInfo> ex) {
    stderr.printf("ERROR: failed to load module %y: %s: %s\n", load_ref, ex.err, ex.desc);
    exit(2);
}

list<string> new_modules = ();
foreach string name in (registry.getProcessModules()) {
    if (!exists before{name}) {
        push new_modules, name;
    }
}

if (!exists module_name) {
    if (new_modules.size() == 1) {
        module_name = new_modules[0];
    } else if (!new_modules.size()) {
        module_name = module_ref;
    } else {
        stderr.printf("ERROR: loading %y registered %d plugin modules; pass --module-name\n",
            module_ref, new_modules.size());
        exit(2);
    }
}

list<string> errors = ();
list<string> warnings = ();

list<hash<auto>> types;
list<hash<auto>> ops;
try {
    types = registry.getTypes(module_name);
    ops = registry.getOperations(module_name);
} catch (hash<ExceptionInfo> ex) {
    stderr.printf("ERROR: cannot inspect plugin module %y: %s: %s\n", module_name, ex.err, ex.desc);
    exit(2);
}

if (!types.size()) {
    push errors, sprintf("module %y registers no plugin types", module_name);
}
if (!ops.size()) {
    push errors, sprintf("module %y registers no plugin operations", module_name);
}

hash<auto> type_ids = {};
int max_type_id = -1;
foreach hash<auto> type in (types) {
    int id = type.local_type_id;
    string key = sprintf("%d", id);
    if (id < 0) {
        push errors, sprintf("type %y has negative local_type_id %d", type.type_name, id);
    } else if (exists type_ids{key}) {
        push errors, sprintf("duplicate type local_type_id %d", id);
    }
    type_ids{key} = True;
    if (id > max_type_id) {
        max_type_id = id;
    }

    if (!type.type_name) {
        push errors, sprintf("type local_type_id %d has no type_name", id);
    }
    if (type.serializer_format_version <= 0) {
        push errors, sprintf("type %y has non-positive serializer_format_version %d",
            type.type_name, type.serializer_format_version);
    }
}
for (int i = 0; i <= max_type_id; ++i) {
    string key = sprintf("%d", i);
    if (!exists type_ids{key}) {
        push errors, sprintf("missing type local_type_id %d; local ids should be contiguous", i);
    }
}

hash<auto> op_ids = {};
int max_op_id = -1;
int llvm_ops = 0;
foreach hash<auto> op in (ops) {
    int id = op.local_id;
    string key = sprintf("%d", id);
    if (id < 0) {
        push errors, sprintf("operation %y has negative local_id %d", op.operation_name, id);
    } else if (exists op_ids{key}) {
        push errors, sprintf("duplicate operation local_id %d", id);
    }
    op_ids{key} = True;
    if (id > max_op_id) {
        max_op_id = id;
    }

    if (!op.operation_name) {
        push errors, sprintf("operation local_id %d has no operation_name", id);
    }
    if (!exists KnownHelperAbis{op.helper_abi}) {
        push errors, sprintf("operation %y has unknown helper_abi %y", op.operation_name, op.helper_abi);
    }
    if (!op.runtime_helper_symbol) {
        string msg = sprintf("operation %y has no runtime_helper_symbol; direct helper pointers work in-process but "
            "make QORD/AOT diagnostics less portable", op.operation_name);
        if (require_runtime_symbols) {
            push errors, msg;
        } else {
            push warnings, msg;
        }
    }
    if (op.has_llvm_codegen) {
        ++llvm_ops;
    } else if (require_all_llvm || exists required_llvm_ops{op.operation_name}) {
        push errors, sprintf("operation %y has no accepted LLVM codegen hook", op.operation_name);
    } else if (op.num_extensions && !op.has_llvm_codegen) {
        push warnings, sprintf("operation %y declares extension metadata but has no accepted LLVM codegen hook",
            op.operation_name);
    }
    if (op.has_lowering_pattern && !op.lowering_claimed_node_kinds) {
        push warnings, sprintf("operation %y has a lowering callback without claimed node kinds; it will be called "
            "for every AST node kind", op.operation_name);
    }
    if (op.helper_abi =~ /^DenseBuffer/ && !op.can_vectorize) {
        push warnings, sprintf("dense-buffer operation %y is not marked can_vectorize", op.operation_name);
    }
    if (op.fp_reassociation_allowed && !op.is_associative) {
        push warnings, sprintf("operation %y allows FP reassociation but is not marked is_associative",
            op.operation_name);
    }
    if (!op.primary_type || !op.return_type) {
        push errors, sprintf("operation %y has incomplete reflected type metadata", op.operation_name);
    }
}
for (int i = 0; i <= max_op_id; ++i) {
    string key = sprintf("%d", i);
    if (!exists op_ids{key}) {
        push errors, sprintf("missing operation local_id %d; local ids should be contiguous", i);
    }
}

if (warnings_are_errors && warnings.size()) {
    push errors, sprintf("%d warning(s) treated as errors", warnings.size());
}

foreach string warning in (warnings) {
    stderr.printf("WARN: %s\n", warning);
}
foreach string error in (errors) {
    stderr.printf("ERROR: %s\n", error);
}

if (errors.size()) {
    stderr.printf("FAIL: plugin module %y has %d error(s) and %d warning(s)\n",
        module_name, errors.size(), warnings.size());
    exit(1);
}

printf("PASS: plugin module %y: %d type(s), %d operation(s), %d LLVM hook(s), %d warning(s)\n",
    module_name, types.size(), ops.size(), llvm_ops, warnings.size());
