/*
 * Copyright (c) 2008-2026 Jonathan Schleifer <js@nil.im>
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3.0 only,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3.0 along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#import "OFArray.h"
#import "OFXMLAttribute.h"

#import "LinkLibGenerator.h"

#import "OFInvalidFormatException.h"
#import "OFUnsupportedVersionException.h"

#import "copyright.h"

@implementation LinkLibGenerator
- (instancetype)initWithLibrary: (OFXMLElement *)library
		 implementation: (OFStream *)impl
{
	self = [super init];

	@try {
		OFXMLAttribute *version;

		if (![library.name isEqual: @"amiga-library"] ||
		    library.namespace != nil)
			@throw [OFInvalidFormatException exception];

		if ((version = [library attributeForName: @"version"]) == nil)
			@throw [OFInvalidFormatException exception];

		if (![version.stringValue isEqual: @"1.0"])
			@throw [OFUnsupportedVersionException
			    exceptionWithVersion: version.stringValue];

		_library = objc_retain(library);
		_impl = objc_retain(impl);
	} @catch (id e) {
		objc_release(self);
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	objc_release(_library);
	objc_release(_impl);

	[super dealloc];
}

- (void)generate
{
	OFString *libBase = [_library attributeForName: @"base"].stringValue;
	OFArray OF_GENERIC(OFXMLElement *) *functions;
	size_t funcIndex = 0;

	[_impl writeString: COPYRIGHT];
	[_impl writeString:
	    @"/* This file is automatically generated from amiga-library.xml */"
	    @"\n\n"
	    @"#include \"config.h\"\n"
	    @"\n"];

	for (OFXMLElement *include in [_library elementsForName: @"include"])
		[_impl writeFormat: @"#import \"%@\"\n",
				    include.stringValue];

	[_impl writeFormat: @"\n"
			    @"extern struct Library *%@;\n"
			    @"\n",
			    libBase];

	[_impl writeString:
	    @"#if OF_GCC_VERSION >= 1100\n"
	    @"# pragma GCC diagnostic ignored \"-Warray-parameter\"\n"
	    @"#endif\n"
	    @"\n"];

	functions = [_library elementsForName: @"function"];
	for (OFXMLElement *function in functions) {
		OFString *name =
		    [function attributeForName: @"name"].stringValue;
		OFString *returnType =
		    [function attributeForName: @"return-type"].stringValue;
		OFArray OF_GENERIC(OFXMLElement *) *arguments =
		    [function elementsForName: @"argument"];
		size_t argumentIndex;

		if (returnType == nil)
			returnType = @"void";

		[_impl writeFormat: @"%@ __attribute__((__weak__))\n"
				    @"%@(", returnType, name];

		argumentIndex = 0;
		for (OFXMLElement *argument in
		    [function elementsForName: @"argument"]) {
			OFString *argName =
			    [argument attributeForName: @"name"].stringValue;
			OFString *argType =
			    [argument attributeForName: @"type"].stringValue;

			if (argumentIndex++ > 0)
				[_impl writeString: @", "];

			[_impl writeString: argType];
			if (![argType hasSuffix: @"*"])
				[_impl writeString: @" "];
			[_impl writeString: argName];
		}

		[_impl writeFormat: @")\n"
				    @"{\n"
				    @"\t__asm__ __volatile__ (\n"
				    @"\t    \"mr\t\t%%%%r12, %%0\"\n"
				    @"\t    :: \"r\" (%@) : \"r12\"\n"
				    @"\t);\n"
				    @"\n"
				    @"\t",
				    libBase, libBase];

		if (![returnType isEqual: @"void"])
			[_impl writeString: @"return "];

		[_impl writeString: @"__extension__ (("];
		[_impl writeString: returnType];
		if (![returnType hasSuffix: @"*"])
			[_impl writeString: @" "];
		[_impl writeString: @"(*)("];

		argumentIndex = 0;
		for (OFXMLElement *argument in arguments) {
			OFString *argType =
			    [argument attributeForName: @"type"].stringValue;

			if (argumentIndex++ > 0)
				[_impl writeString: @", "];

			[_impl writeString: argType];
		}

		[_impl writeFormat: @"))*(void **)(((uintptr_t)%@) - %zu))(",
				    libBase, 28 + funcIndex * 6];

		argumentIndex = 0;
		for (OFXMLElement *argument in
		    [function elementsForName: @"argument"]) {
			OFString *argName =
			    [argument attributeForName: @"name"].stringValue;

			if (argumentIndex++ > 0)
				[_impl writeString: @", "];

			[_impl writeString: argName];
		}

		[_impl writeString: @");\n"];

		if ([function attributeForName: @"noreturn"] != nil)
			[_impl writeString: @"\n\tOF_UNREACHABLE\n"];

		[_impl writeString: @"}\n"];

		if (++funcIndex < functions.count)
			[_impl writeString: @"\n"];
	}
}
@end
