• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daisytuner / docc / 21746009216

06 Feb 2026 09:43AM UTC coverage: 66.359% (-0.1%) from 66.484%
21746009216

push

github

web-flow
Merge pull request #506 from daisytuner/npbench-crc16

adds crc16 npbench benchmark

53 of 130 new or added lines in 3 files covered. (40.77%)

1 existing line in 1 file now uncovered.

23114 of 34832 relevant lines covered (66.36%)

375.27 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.54
/python/docc/python/python_program.py
1
import inspect
4✔
2
import shutil
4✔
3
import textwrap
4✔
4
import ast
4✔
5
import os
4✔
6
import getpass
4✔
7
import hashlib
4✔
8
import numpy as np
4✔
9
from typing import Annotated, get_origin, get_args, Any, Optional
4✔
10

11
from docc.sdfg import (
4✔
12
    Scalar,
13
    PrimitiveType,
14
    Pointer,
15
    Structure,
16
    Array,
17
    Type,
18
    StructuredSDFG,
19
    StructuredSDFGBuilder,
20
)
21
from docc.compiler.docc_program import DoccProgram
4✔
22
from docc.compiler.compiled_sdfg import CompiledSDFG
4✔
23
from docc.python.ast_parser import ASTParser
4✔
24

25
# Global RPC context for scheduling SDFGs
26
sdfg_rpc_context = None
4✔
27

28

29
def _compile_wrapper(self, output_folder=None):
4✔
30
    """Wrapper to allow StructuredSDFG.compile() to return a CompiledSDFG."""
31
    lib_path = self._compile(output_folder)
×
32
    return CompiledSDFG(lib_path, self)
×
33

34

35
# Monkey-patch StructuredSDFG to add compile method
36
StructuredSDFG.compile = _compile_wrapper
4✔
37

38

39
def _map_python_type(dtype):
4✔
40
    """Map Python/numpy types to SDFG types."""
41
    # If it is already a sdfg Type, return it
42
    if isinstance(dtype, Type):
4✔
43
        return dtype
×
44

45
    # Handle Annotated for Arrays
46
    if get_origin(dtype) is Annotated:
4✔
47
        args = get_args(dtype)
4✔
48
        base_type = args[0]
4✔
49
        metadata = args[1:]
4✔
50

51
        if base_type is np.ndarray:
4✔
52
            # Convention: Annotated[np.ndarray, shape, dtype]
53
            shape = metadata[0]
4✔
54
            elem_type = Scalar(PrimitiveType.Double)  # Default
4✔
55

56
            if len(metadata) > 1:
4✔
57
                possible_dtype = metadata[1]
4✔
58
                elem_type = _map_python_type(possible_dtype)
4✔
59

60
            return Pointer(elem_type)
4✔
61

62
    # Handle numpy.ndarray[Shape, DType]
63
    if get_origin(dtype) is np.ndarray:
4✔
64
        args = get_args(dtype)
×
65
        # args[0] is shape, args[1] is dtype
66
        if len(args) >= 2:
×
67
            elem_type = _map_python_type(args[1])
×
68
            return Pointer(elem_type)
×
69

70
    # Simple mapping for python types
71
    if dtype is float or dtype is np.float64:
4✔
72
        return Scalar(PrimitiveType.Double)
4✔
73
    elif dtype is np.float32:
4✔
UNCOV
74
        return Scalar(PrimitiveType.Float)
×
75
    elif dtype is bool or dtype is np.bool_:
4✔
76
        return Scalar(PrimitiveType.Bool)
4✔
77
    elif dtype is int or dtype is np.int64:
4✔
78
        return Scalar(PrimitiveType.Int64)
4✔
79
    elif dtype is np.int32:
4✔
80
        return Scalar(PrimitiveType.Int32)
4✔
81
    elif dtype is np.int16:
4✔
NEW
82
        return Scalar(PrimitiveType.Int16)
×
83
    elif dtype is np.int8:
4✔
NEW
84
        return Scalar(PrimitiveType.Int8)
×
85
    elif dtype is np.uint64:
4✔
NEW
86
        return Scalar(PrimitiveType.UInt64)
×
87
    elif dtype is np.uint32:
4✔
NEW
88
        return Scalar(PrimitiveType.UInt32)
×
89
    elif dtype is np.uint16:
4✔
NEW
90
        return Scalar(PrimitiveType.UInt16)
×
91
    elif dtype is np.uint8:
4✔
NEW
92
        return Scalar(PrimitiveType.UInt8)
×
93

94
    # Handle Python classes - map to Structure type
95
    if inspect.isclass(dtype):
4✔
96
        # Use the class name as the structure name
97
        return Pointer(Structure(dtype.__name__))
4✔
98

99
    return dtype
×
100

101

102
class PythonProgram(DoccProgram):
4✔
103

104
    def __init__(
4✔
105
        self,
106
        func,
107
        target: str = "none",
108
        category: str = "server",
109
        instrumentation_mode: Optional[str] = None,
110
        capture_args: Optional[bool] = None,
111
    ):
112
        super().__init__(
4✔
113
            name=func.__name__,
114
            target=target,
115
            category=category,
116
            instrumentation_mode=instrumentation_mode,
117
            capture_args=capture_args,
118
        )
119
        self.func = func
4✔
120
        self._last_structure_member_info = {}
4✔
121

122
    def __call__(self, *args: Any) -> Any:
4✔
123
        # JIT compile and run
124
        compiled = self.compile(*args)
4✔
125
        res = compiled(*args)
4✔
126

127
        # Handle return value conversion based on annotation
128
        sig = inspect.signature(self.func)
4✔
129
        ret_annotation = sig.return_annotation
4✔
130

131
        if ret_annotation is not inspect.Signature.empty:
4✔
132
            if get_origin(ret_annotation) is Annotated:
4✔
133
                type_args = get_args(ret_annotation)
4✔
134
                if len(type_args) >= 1 and type_args[0] is np.ndarray:
4✔
135
                    shape = None
4✔
136
                    if len(type_args) >= 2:
4✔
137
                        shape = type_args[1]
4✔
138

139
                    if shape is not None:
4✔
140
                        try:
4✔
141
                            return np.ctypeslib.as_array(res, shape=shape)
4✔
142
                        except Exception:
×
143
                            pass
×
144

145
        # Try to infer return shape from metadata
146
        if hasattr(compiled, "get_return_shape"):
4✔
147
            shape = compiled.get_return_shape(*args)
4✔
148
            if shape is not None:
4✔
149
                try:
×
150
                    return np.ctypeslib.as_array(res, shape=shape)
×
151
                except Exception:
×
152
                    pass
×
153

154
        return res
4✔
155

156
    def compile(
4✔
157
        self,
158
        *args: Any,
159
        output_folder: Optional[str] = None,
160
        instrumentation_mode: Optional[str] = None,
161
        capture_args: Optional[bool] = None,
162
    ) -> CompiledSDFG:
163
        original_output_folder = output_folder
4✔
164

165
        # Resolve options
166
        if instrumentation_mode is None:
4✔
167
            instrumentation_mode = self.instrumentation_mode
4✔
168
        if capture_args is None:
4✔
169
            capture_args = self.capture_args
4✔
170

171
        # Check environment variable DOCC_CI
172
        docc_ci = os.environ.get("DOCC_CI", "")
4✔
173
        if docc_ci:
4✔
174
            if docc_ci == "regions":
×
175
                if instrumentation_mode is None:
×
176
                    instrumentation_mode = "ols"
×
177
            elif docc_ci == "arg-capture":
×
178
                if capture_args is None:
×
179
                    capture_args = True
×
180
            else:
181
                # Full mode (or unknown value treated as full)
182
                if instrumentation_mode is None:
×
183
                    instrumentation_mode = "ols"
×
184
                if capture_args is None:
×
185
                    capture_args = True
×
186

187
        # Defaults
188
        if instrumentation_mode is None:
4✔
189
            instrumentation_mode = ""
4✔
190
        if capture_args is None:
4✔
191
            capture_args = False
4✔
192

193
        # 1. Analyze arguments and shapes
194
        arg_types = []
4✔
195
        shape_values = []  # List of unique shape values found
4✔
196
        shape_sources = []  # List of (arg_idx, dim_idx) for each unique shape value
4✔
197

198
        # Mapping from (arg_idx, dim_idx) -> unique_shape_idx
199
        arg_shape_mapping = {}
4✔
200

201
        # First pass: collect scalar integer arguments and their values
202
        sig = inspect.signature(self.func)
4✔
203
        params = list(sig.parameters.items())
4✔
204
        scalar_int_params = {}  # Maps value -> parameter name (first one wins)
4✔
205
        for i, ((name, param), arg) in enumerate(zip(params, args)):
4✔
206
            if isinstance(arg, (int, np.integer)) and not isinstance(
4✔
207
                arg, (bool, np.bool_)
208
            ):
209
                val = int(arg)
4✔
210
                if val not in scalar_int_params:
4✔
211
                    scalar_int_params[val] = name
4✔
212

213
        for i, arg in enumerate(args):
4✔
214
            t = self._infer_type(arg)
4✔
215
            arg_types.append(t)
4✔
216

217
            if isinstance(arg, np.ndarray):
4✔
218
                for dim_idx, dim_val in enumerate(arg.shape):
4✔
219
                    # Check if we've seen this value
220
                    if dim_val in shape_values:
4✔
221
                        # Reuse
222
                        u_idx = shape_values.index(dim_val)
4✔
223
                    else:
224
                        # New
225
                        u_idx = len(shape_values)
4✔
226
                        shape_values.append(dim_val)
4✔
227
                        shape_sources.append((i, dim_idx))
4✔
228

229
                    arg_shape_mapping[(i, dim_idx)] = u_idx
4✔
230

231
        # Detect scalar-shape equivalences: which shape indices have a matching scalar param
232
        # Maps unique_shape_idx -> scalar parameter name
233
        shape_to_scalar = {}
4✔
234
        for s_idx, s_val in enumerate(shape_values):
4✔
235
            if s_val in scalar_int_params:
4✔
236
                shape_to_scalar[s_idx] = scalar_int_params[s_val]
4✔
237

238
        # 2. Signature - include scalar-shape equivalences for correct caching
239
        mapping_sig = sorted(arg_shape_mapping.items())
4✔
240
        equiv_sig = sorted(shape_to_scalar.items())
4✔
241
        type_sig = ", ".join(self._type_to_str(t) for t in arg_types)
4✔
242
        signature = f"{type_sig}|{mapping_sig}|{equiv_sig}"
4✔
243

244
        if output_folder is None:
4✔
245
            filename = inspect.getsourcefile(self.func)
4✔
246
            hash_input = f"{filename}|{self.name}|{self.target}|{self.category}|{self.capture_args}|{self.instrumentation_mode}|{signature}".encode(
4✔
247
                "utf-8"
248
            )
249
            stable_id = hashlib.sha256(hash_input).hexdigest()[:16]
4✔
250

251
            docc_tmp = os.environ.get("DOCC_TMP")
4✔
252
            if docc_tmp:
4✔
253
                output_folder = f"{docc_tmp}/{self.name}-{stable_id}"
×
254
            else:
255
                user = getpass.getuser()
4✔
256
                output_folder = f"/tmp/{user}/DOCC/{self.name}-{stable_id}"
4✔
257

258
        if original_output_folder is None and signature in self.cache:
4✔
259
            return self.cache[signature]
4✔
260

261
        # 3. Build SDFG
262
        if os.path.exists(output_folder):
4✔
263
            # Multiple python processes running the same code?
264
            shutil.rmtree(output_folder)
4✔
265
        sdfg, out_args, out_shapes = self._build_sdfg(
4✔
266
            arg_types, args, arg_shape_mapping, len(shape_values), shape_to_scalar
267
        )
268
        sdfg.validate()
4✔
269
        sdfg.expand()
4✔
270
        sdfg.simplify()
4✔
271

272
        if self.target != "none":
4✔
273
            sdfg.normalize()
4✔
274

275
        sdfg.dump(output_folder)
4✔
276

277
        # Schedule if target is specified
278
        if self.target != "none":
4✔
279
            sdfg.schedule(self.target, self.category, sdfg_rpc_context)
4✔
280

281
        self.last_sdfg = sdfg
4✔
282

283
        lib_path = sdfg._compile(
4✔
284
            output_folder=output_folder,
285
            target=self.target,
286
            instrumentation_mode=instrumentation_mode,
287
            capture_args=capture_args,
288
        )
289

290
        # 5. Create CompiledSDFG
291
        compiled = CompiledSDFG(
4✔
292
            lib_path,
293
            sdfg,
294
            shape_sources,
295
            self._last_structure_member_info,
296
            out_args,
297
            out_shapes,
298
        )
299

300
        # Cache if using default output folder
301
        if original_output_folder is None:
4✔
302
            self.cache[signature] = compiled
4✔
303

304
        return compiled
4✔
305

306
    def to_sdfg(self, *args: Any) -> StructuredSDFG:
4✔
307
        arg_types = [self._infer_type(arg) for arg in args]
×
308

309
        # Build shape mapping
310
        shape_values = []
×
311
        shape_sources = []
×
312
        arg_shape_mapping = {}
×
313

314
        sig = inspect.signature(self.func)
×
315
        params = list(sig.parameters.items())
×
316
        scalar_int_params = {}
×
317
        for i, ((name, param), arg) in enumerate(zip(params, args)):
×
318
            if isinstance(arg, (int, np.integer)) and not isinstance(
×
319
                arg, (bool, np.bool_)
320
            ):
321
                val = int(arg)
×
322
                if val not in scalar_int_params:
×
323
                    scalar_int_params[val] = name
×
324

325
        for i, arg in enumerate(args):
×
326
            if isinstance(arg, np.ndarray):
×
327
                for dim_idx, dim_val in enumerate(arg.shape):
×
328
                    if dim_val in shape_values:
×
329
                        u_idx = shape_values.index(dim_val)
×
330
                    else:
331
                        u_idx = len(shape_values)
×
332
                        shape_values.append(dim_val)
×
333
                        shape_sources.append((i, dim_idx))
×
334
                    arg_shape_mapping[(i, dim_idx)] = u_idx
×
335

336
        shape_to_scalar = {}
×
337
        for s_idx, s_val in enumerate(shape_values):
×
338
            if s_val in scalar_int_params:
×
339
                shape_to_scalar[s_idx] = scalar_int_params[s_val]
×
340

341
        sdfg, _, _ = self._build_sdfg(
×
342
            arg_types, args, arg_shape_mapping, len(shape_values), shape_to_scalar
343
        )
344
        return sdfg
×
345

346
    def _convert_inputs(self, args: tuple) -> tuple:
4✔
347
        return args
×
348

349
    def _convert_outputs(self, result: Any, original_args: tuple) -> Any:
4✔
350
        return result
×
351

352
    def _get_signature(self, arg_types):
4✔
353
        return ", ".join(self._type_to_str(t) for t in arg_types)
×
354

355
    def _type_to_str(self, t):
4✔
356
        if isinstance(t, Scalar):
4✔
357
            return f"Scalar({t.primitive_type})"
4✔
358
        elif isinstance(t, Array):
4✔
359
            return f"Array({self._type_to_str(t.element_type)}, {t.num_elements})"
×
360
        elif isinstance(t, Pointer):
4✔
361
            return f"Pointer({self._type_to_str(t.pointee_type)})"
4✔
362
        elif isinstance(t, Structure):
4✔
363
            return f"Structure({t.name})"
4✔
364
        return str(t)
×
365

366
    def _infer_type(self, arg):
4✔
367
        if isinstance(arg, (float, np.float64)):
4✔
368
            return Scalar(PrimitiveType.Double)
4✔
369
        elif isinstance(arg, np.float32):
4✔
370
            return Scalar(PrimitiveType.Float)
4✔
371
        elif isinstance(arg, (bool, np.bool_)):
4✔
372
            return Scalar(PrimitiveType.Bool)
4✔
373
        elif isinstance(arg, (int, np.int64)):
4✔
374
            return Scalar(PrimitiveType.Int64)
4✔
375
        elif isinstance(arg, np.int32):
4✔
376
            return Scalar(PrimitiveType.Int32)
4✔
377
        elif isinstance(arg, np.int16):
4✔
NEW
378
            return Scalar(PrimitiveType.Int16)
×
379
        elif isinstance(arg, np.int8):
4✔
NEW
380
            return Scalar(PrimitiveType.Int8)
×
381
        elif isinstance(arg, np.uint64):
4✔
NEW
382
            return Scalar(PrimitiveType.UInt64)
×
383
        elif isinstance(arg, np.uint32):
4✔
NEW
384
            return Scalar(PrimitiveType.UInt32)
×
385
        elif isinstance(arg, np.uint16):
4✔
NEW
386
            return Scalar(PrimitiveType.UInt16)
×
387
        elif isinstance(arg, np.uint8):
4✔
NEW
388
            return Scalar(PrimitiveType.UInt8)
×
389
        elif isinstance(arg, np.ndarray):
4✔
390
            # Map dtype
391
            if arg.dtype == np.float64:
4✔
392
                elem_type = Scalar(PrimitiveType.Double)
4✔
393
            elif arg.dtype == np.float32:
4✔
394
                elem_type = Scalar(PrimitiveType.Float)
4✔
395
            elif arg.dtype == np.bool_:
4✔
396
                elem_type = Scalar(PrimitiveType.Bool)
4✔
397
            elif arg.dtype == np.int64:
4✔
398
                elem_type = Scalar(PrimitiveType.Int64)
4✔
399
            elif arg.dtype == np.int32:
4✔
400
                elem_type = Scalar(PrimitiveType.Int32)
4✔
NEW
401
            elif arg.dtype == np.int16:
×
NEW
402
                elem_type = Scalar(PrimitiveType.Int16)
×
NEW
403
            elif arg.dtype == np.int8:
×
NEW
404
                elem_type = Scalar(PrimitiveType.Int8)
×
NEW
405
            elif arg.dtype == np.uint64:
×
NEW
406
                elem_type = Scalar(PrimitiveType.UInt64)
×
NEW
407
            elif arg.dtype == np.uint32:
×
NEW
408
                elem_type = Scalar(PrimitiveType.UInt32)
×
NEW
409
            elif arg.dtype == np.uint16:
×
NEW
410
                elem_type = Scalar(PrimitiveType.UInt16)
×
NEW
411
            elif arg.dtype == np.uint8:
×
NEW
412
                elem_type = Scalar(PrimitiveType.UInt8)
×
413
            else:
414
                raise ValueError(f"Unsupported numpy dtype: {arg.dtype}")
×
415

416
            return Pointer(elem_type)
4✔
417
        elif isinstance(arg, str):
4✔
418
            # Explicitly reject strings - they are not supported
419
            raise ValueError(f"Unsupported argument type: {type(arg)}")
4✔
420
        else:
421
            # Check if it's a class instance
422
            if hasattr(arg, "__class__") and not isinstance(arg, type):
4✔
423
                # It's an instance of a class, return pointer to Structure
424
                return Pointer(Structure(arg.__class__.__name__))
4✔
425
            raise ValueError(f"Unsupported argument type: {type(arg)}")
×
426

427
    def _build_sdfg(
4✔
428
        self,
429
        arg_types,
430
        args,
431
        arg_shape_mapping,
432
        num_unique_shapes,
433
        shape_to_scalar=None,
434
    ):
435
        if shape_to_scalar is None:
4✔
436
            shape_to_scalar = {}
4✔
437
        sig = inspect.signature(self.func)
4✔
438

439
        # Handle return type - always void for SDFG, output args used for returns
440
        return_type = Scalar(PrimitiveType.Void)
4✔
441
        infer_return_type = True
4✔
442

443
        # Parse return annotation to determine output arguments if possible
444
        explicit_returns = []
4✔
445
        if sig.return_annotation is not inspect.Signature.empty:
4✔
446
            infer_return_type = False
4✔
447

448
            # Helper to normalize annotation to list of types
449
            def normalize_annotation(ann):
4✔
450
                # Handle Tuple[type, ...]
451
                origin = get_origin(ann)
4✔
452
                if origin is tuple:
4✔
453
                    type_args = get_args(ann)
×
454
                    # Tuple[()] or Tuple w/o args
455
                    if not type_args:
×
456
                        return []
×
457
                    # Tuple[int, float]
458
                    if len(type_args) > 0 and type_args[-1] is not Ellipsis:
×
459
                        return [_map_python_type(t) for t in type_args]
×
460
                    # Tuple[int, ...] - not supported for fixed number of returns yet?
461
                    # For now assume fixed tuple
462
                    return [_map_python_type(t) for t in type_args]
×
463
                else:
464
                    return [_map_python_type(ann)]
4✔
465

466
            explicit_returns = normalize_annotation(sig.return_annotation)
4✔
467
            for rt in explicit_returns:
4✔
468
                if not isinstance(rt, Type):
4✔
469
                    # Fallback if map failed (e.g. invalid annotation)
470
                    infer_return_type = True
×
471
                    explicit_returns = []
×
472
                    break
×
473

474
        builder = StructuredSDFGBuilder(f"{self.name}_sdfg", return_type)
4✔
475

476
        # Add pre-defined return arguments if we know them
477
        if not infer_return_type:
4✔
478
            for i, dtype in enumerate(explicit_returns):
4✔
479
                # Scalar -> Pointer(Scalar)
480
                # Array -> Already Pointer(Scalar). Keep it.
481
                arg_type = dtype
4✔
482
                if isinstance(dtype, Scalar):
4✔
483
                    arg_type = Pointer(dtype)
4✔
484

485
                builder.add_container(f"_docc_ret_{i}", arg_type, is_argument=True)
4✔
486

487
        # Register structure types for any class arguments
488
        # Also track member name to index mapping for each structure
489
        structures_to_register = {}
4✔
490
        structure_member_info = {}  # Maps struct_name -> {member_name: (index, type)}
4✔
491
        for i, (arg, dtype) in enumerate(zip(args, arg_types)):
4✔
492
            if isinstance(dtype, Pointer) and dtype.has_pointee_type():
4✔
493
                pointee = dtype.pointee_type
4✔
494
                if isinstance(pointee, Structure):
4✔
495
                    struct_name = pointee.name
4✔
496
                    if struct_name not in structures_to_register:
4✔
497
                        # Get class from arg to introspect members
498
                        if hasattr(arg, "__dict__"):
4✔
499
                            # Use __dict__ to get only instance attributes
500
                            # Sort by name to ensure consistent ordering
501
                            # Note: This alphabetical ordering is used to define the
502
                            # structure layout and must match the order expected by
503
                            # the backend code generation
504
                            member_types = []
4✔
505
                            member_names = []
4✔
506
                            for attr_name, attr_value in sorted(arg.__dict__.items()):
4✔
507
                                if not attr_name.startswith("_"):
4✔
508
                                    # Infer member type from instance attribute
509
                                    # Check bool before int since bool is subclass of int
510
                                    member_type = None
4✔
511
                                    if isinstance(attr_value, bool):
4✔
512
                                        member_type = Scalar(PrimitiveType.Bool)
×
513
                                    elif isinstance(attr_value, (int, np.int64)):
4✔
514
                                        member_type = Scalar(PrimitiveType.Int64)
×
515
                                    elif isinstance(attr_value, (float, np.float64)):
4✔
516
                                        member_type = Scalar(PrimitiveType.Double)
4✔
517
                                    elif isinstance(attr_value, np.int32):
×
518
                                        member_type = Scalar(PrimitiveType.Int32)
×
519
                                    elif isinstance(attr_value, np.float32):
×
520
                                        member_type = Scalar(PrimitiveType.Float)
×
521
                                    # TODO: Consider using np.integer and np.floating abstract types
522
                                    # for more comprehensive numpy type coverage
523
                                    # TODO: Add support for nested structures and arrays
524

525
                                    if member_type is not None:
4✔
526
                                        member_types.append(member_type)
4✔
527
                                        member_names.append(attr_name)
4✔
528

529
                            if member_types:
4✔
530
                                structures_to_register[struct_name] = member_types
4✔
531
                                # Build member name to (index, type) mapping
532
                                structure_member_info[struct_name] = {
4✔
533
                                    name: (idx, mtype)
534
                                    for idx, (name, mtype) in enumerate(
535
                                        zip(member_names, member_types)
536
                                    )
537
                                }
538

539
        # Store structure_member_info for later use in CompiledSDFG
540
        self._last_structure_member_info = structure_member_info
4✔
541

542
        # Register all discovered structures with the builder
543
        for struct_name, member_types in structures_to_register.items():
4✔
544
            builder.add_structure(struct_name, member_types)
4✔
545

546
        # Register arguments
547
        params = list(sig.parameters.items())
4✔
548
        if len(params) != len(arg_types):
4✔
549
            raise ValueError(
×
550
                f"Argument count mismatch: expected {len(params)}, got {len(arg_types)}"
551
            )
552

553
        array_info = {}
4✔
554

555
        # Add regular arguments
556
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
557
            builder.add_container(name, dtype, is_argument=True)
4✔
558

559
            # If it's an array, prepare shape info
560
            if isinstance(arg, np.ndarray):
4✔
561
                shapes = []
4✔
562
                for dim_idx in range(arg.ndim):
4✔
563
                    u_idx = arg_shape_mapping[(i, dim_idx)]
4✔
564
                    # Use scalar parameter name if there's an equivalence, otherwise _sX
565
                    if u_idx in shape_to_scalar:
4✔
566
                        shapes.append(shape_to_scalar[u_idx])
4✔
567
                    else:
568
                        shapes.append(f"_s{u_idx}")
4✔
569

570
                array_info[name] = {"ndim": arg.ndim, "shapes": shapes}
4✔
571

572
        # Add unified shape arguments only for shapes without scalar equivalents
573
        for i in range(num_unique_shapes):
4✔
574
            if i not in shape_to_scalar:
4✔
575
                builder.add_container(
4✔
576
                    f"_s{i}", Scalar(PrimitiveType.Int64), is_argument=True
577
                )
578

579
        # Create symbol table for parser
580
        symbol_table = {}
4✔
581
        for i, ((name, param), dtype, arg) in enumerate(zip(params, arg_types, args)):
4✔
582
            symbol_table[name] = dtype
4✔
583

584
        for i in range(num_unique_shapes):
4✔
585
            if i not in shape_to_scalar:
4✔
586
                symbol_table[f"_s{i}"] = Scalar(PrimitiveType.Int64)
4✔
587

588
        # Parse AST
589
        source_lines, start_line = inspect.getsourcelines(self.func)
4✔
590
        source = textwrap.dedent("".join(source_lines))
4✔
591
        tree = ast.parse(source)
4✔
592
        ast.increment_lineno(tree, start_line - 1)
4✔
593
        func_def = tree.body[0]
4✔
594

595
        filename = inspect.getsourcefile(self.func)
4✔
596
        function_name = self.func.__name__
4✔
597

598
        parser = ASTParser(
4✔
599
            builder,
600
            array_info,
601
            symbol_table,
602
            filename,
603
            function_name,
604
            infer_return_type=infer_return_type,
605
            globals_dict=self.func.__globals__,
606
            structure_member_info=structure_member_info,
607
        )
608
        for node in func_def.body:
4✔
609
            parser.visit(node)
4✔
610

611
        sdfg = builder.move()
4✔
612
        # Mark return arguments metadata
613
        out_args = []
4✔
614
        for name in sdfg.arguments:
4✔
615
            if name.startswith("_docc_ret_"):
4✔
616
                out_args.append(name)
4✔
617

618
        return sdfg, out_args, parser.captured_return_shapes
4✔
619

620

621
def native(
4✔
622
    func=None,
623
    *,
624
    target="none",
625
    category="desktop",
626
    instrumentation_mode=None,
627
    capture_args=None,
628
):
629
    """Decorator to create a PythonProgram from a Python function.
630

631
    Example:
632
        @native
633
        def my_function(x: np.ndarray) -> np.ndarray:
634
            return x * 2
635

636
        result = my_function(np.array([1.0, 2.0, 3.0]))
637
    """
638
    if func is None:
4✔
639
        return lambda f: PythonProgram(
4✔
640
            f,
641
            target=target,
642
            category=category,
643
            instrumentation_mode=instrumentation_mode,
644
            capture_args=capture_args,
645
        )
646
    return PythonProgram(
4✔
647
        func,
648
        target=target,
649
        category=category,
650
        instrumentation_mode=instrumentation_mode,
651
        capture_args=capture_args,
652
    )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc