From cfc79b1ef4c4e654d109d708923a2c7edf23f78d Mon Sep 17 00:00:00 2001 From: Mario Ruiz <11815099+mariodruiz@users.noreply.github.com> Date: Tue, 15 Oct 2024 17:16:14 +0100 Subject: [PATCH] Check that kernel source code has extern C defined (#70) * Verify that kernel code is wrapped in extern C * Remove curly braces * Add breakline * Change raise type * Fix checks * Return RunTime error * Check construct * Use Syntax error * Change way we do pytest * Only check if extern C exists * Remove unused check --- npu/build/kernel.py | 9 +++++++++ tests/test_externc.py | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 tests/test_externc.py diff --git a/npu/build/kernel.py b/npu/build/kernel.py index 188636a..066aa24 100644 --- a/npu/build/kernel.py +++ b/npu/build/kernel.py @@ -12,6 +12,7 @@ from .port import BufferPort, RTPPort from typing import Optional, Callable, List, Dict import re +import warnings class Kernel(KernelMeta): @@ -56,6 +57,7 @@ def __init__(self, srccode : str, behavioralfx:Optional[Callable]=None, top_func self.kb = KernelObjectBuilder(self.ktype, self.srccode, self.srcfile) self._main_function_sanity_check() + self._extern_c_check() self._expose_ports() def _expose_ports(self)->None: @@ -96,6 +98,13 @@ def _main_function_sanity_check(self)->None: if not self._main_function['rtnType'] == "void": raise RuntimeError(f"The return type of the top_level function should be void not {self._main_function['rtnType']}") + def _extern_c_check(self): + """Verify that extern C is used""" + tight_code = self.srccode.replace(' ', '').replace(' ', '') + if 'extern"C"' not in tight_code: + raise SyntaxError('extern "C" not found. Top level function ' + 'should be wrapped by extern "C"') + def display(self)->None: """Render the kernel code in a jupyter notebook.""" from IPython.display import display, Code diff --git a/tests/test_externc.py b/tests/test_externc.py new file mode 100644 index 0000000..7792852 --- /dev/null +++ b/tests/test_externc.py @@ -0,0 +1,27 @@ +# Copyright 2024 Advanced Micro Devices, Inc. +# SPDX-License-Identifier: MIT + +import pytest +from npu.build.kernel import Kernel +from npu.lib import Plus1 + + +kernel_src = Plus1().srccode + +kernel_src1 = kernel_src.replace('\n\n}', '') + + +def test_externc_good(): + krnl_obj = Kernel(kernel_src) + krnl_obj.build() + assert krnl_obj + + +@pytest.mark.parametrize('replacewith', ['']) +def test_externc_bad(replacewith): + src_code = kernel_src1.replace('extern "C" {', replacewith) + + with pytest.raises(SyntaxError) as excinfo: + _ = Kernel(src_code) + + assert 'extern "C" not found.' in str(excinfo.value)