Skip to content

Commit 91f2018

Browse files
committed
compiler: convert all in visitors to f-string
1 parent ad7271f commit 91f2018

6 files changed

Lines changed: 91 additions & 79 deletions

File tree

devito/arch/compiler.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,10 @@ def __init__(self):
185185
_cstd = 'c99'
186186

187187
def __init__(self, **kwargs):
188-
_name = kwargs.pop('name', self.__class__.__name__)
189-
if isinstance(_name, Compiler):
190-
_name = _name.name
191-
self._name = _name
188+
name = kwargs.pop('name', self.__class__.__name__)
189+
if isinstance(name, Compiler):
190+
name = name.name
191+
self._name = name
192192

193193
super().__init__(**kwargs)
194194

devito/data/allocators.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import abc
2-
from functools import reduce
3-
from operator import mul
42
import ctypes
53
from ctypes.util import find_library
64
import mmap
@@ -11,7 +9,7 @@
119

1210
from devito.logger import logger
1311
from devito.parameters import configuration
14-
from devito.tools import is_integer, dtype_alloc_ctype
12+
from devito.tools import is_integer, infer_datasize
1513

1614
__all__ = ['ALLOC_ALIGNED', 'ALLOC_NUMA_LOCAL', 'ALLOC_NUMA_ANY',
1715
'ALLOC_KNL_MCDRAM', 'ALLOC_KNL_DRAM', 'ALLOC_GUARD',
@@ -92,8 +90,7 @@ def initialize(cls):
9290
return
9391

9492
def alloc(self, shape, dtype, padding=0):
95-
ctype, c_scale = dtype_alloc_ctype(dtype)
96-
datasize = int(reduce(mul, shape) * c_scale)
93+
ctype, datasize = infer_datasize(dtype, shape)
9794

9895
# Add padding, if any
9996
try:

devito/ir/iet/visitors.py

Lines changed: 70 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -80,23 +80,24 @@ def indent(self):
8080
return ' ' * self._depth
8181

8282
def visit_Node(self, o):
83-
return self.indent + '<%s>' % o.__class__.__name__
83+
return self.indent + f'<{o.__class__.__name__}>'
8484

8585
def visit_Generable(self, o):
86-
body = ' %s' % str(o) if self.verbose else ''
87-
return self.indent + '<C.%s%s>' % (o.__class__.__name__, body)
86+
body = f" {str(o) if self.verbose else ''}"
87+
return self.indent + f'<C.{o.__class__.__name__}{body}>'
8888

8989
def visit_Callable(self, o):
9090
self._depth += 1
9191
body = self._visit(o.children)
9292
self._depth -= 1
93-
return self.indent + '<Callable %s>\n%s' % (o.name, body)
93+
return self.indent + f'<Callable {o.name}>\n{body}'
9494

9595
def visit_CallableBody(self, o):
9696
self._depth += 1
9797
body = [self._visit(o.init), self._visit(o.unpacks), self._visit(o.body)]
9898
self._depth -= 1
99-
return self.indent + "%s\n%s" % (o.__repr__(), '\n'.join([i for i in body if i]))
99+
cbody = '\n'.join([i for i in body if i])
100+
return self.indent + f"{o.__repr__()}\n{cbody}"
100101

101102
def visit_list(self, o):
102103
return ('\n').join([self._visit(i) for i in o])
@@ -111,62 +112,67 @@ def visit_List(self, o):
111112
else:
112113
body = [self._visit(o.body)]
113114
self._depth -= 1
114-
return self.indent + "%s\n%s" % (o.__repr__(), '\n'.join(body))
115+
cbody = '\n'.join(body)
116+
return self.indent + f"{o.__repr__()}\n{cbody}"
115117

116118
def visit_TimedList(self, o):
117119
self._depth += 1
118120
body = [self._visit(o.body)]
119121
self._depth -= 1
120-
return self.indent + "%s\n%s" % (o.__repr__(), '\n'.join(body))
122+
cbody = '\n'.join(body)
123+
return self.indent + f"{o.__repr__()}\n{cbody}"
121124

122125
def visit_Iteration(self, o):
123126
self._depth += 1
124127
body = self._visit(o.children)
125128
self._depth -= 1
126129
if self.verbose:
127-
detail = '::%s::%s' % (o.index, o.limits)
130+
detail = f'::{o.index}::{o.limits}'
128131
props = [str(i) for i in o.properties]
129-
props = '[%s] ' % ','.join(props) if props else ''
132+
if props:
133+
cprops = ','.join(props)
134+
props = f'[{cprops}] '
135+
else:
136+
props = ''
130137
else:
131138
detail, props = '', ''
132-
return self.indent + "<%sIteration %s%s>\n%s" % (props, o.dim.name, detail, body)
139+
return self.indent + f"<{props}Iteration {o.dim.name}{detail}>\n{body}"
133140

134141
def visit_While(self, o):
135142
self._depth += 1
136143
body = self._visit(o.children)
137144
self._depth -= 1
138-
return self.indent + "<While %s>\n%s" % (o.condition, body)
145+
return self.indent + f"<While {o.condition}>\n{body}"
139146

140147
def visit_Expression(self, o):
141148
if self.verbose:
142-
body = "%s = %s" % (o.expr.lhs, o.expr.rhs)
143-
return self.indent + "<Expression %s>" % body
149+
body = f"{o.expr.lhs} = {o.expr.rhs}"
150+
return self.indent + f"<Expression {body}>"
144151
else:
145152
return self.indent + str(o)
146153

147154
def visit_AugmentedExpression(self, o):
148155
if self.verbose:
149-
body = "%s %s= %s" % (o.expr.lhs, o.op, o.expr.rhs)
150-
return self.indent + "<%s %s>" % (o.__class__.__name__, body)
156+
body = f"{o.expr.lhs} {o.op}= {o.expr.rhs}"
157+
return self.indent + f"<{o.__class__.__name__} {body}>"
151158
else:
152159
return self.indent + str(o)
153160

154161
def visit_HaloSpot(self, o):
155162
self._depth += 1
156163
body = self._visit(o.children)
157164
self._depth -= 1
158-
return self.indent + "%s\n%s" % (o.__repr__(), body)
165+
return self.indent + f"{o.__repr__()}\n{body}"
159166

160167
def visit_Conditional(self, o):
161168
self._depth += 1
162169
then_body = self._visit(o.then_body)
163170
self._depth -= 1
164171
if o.else_body:
165172
else_body = self._visit(o.else_body)
166-
return self.indent + "<If %s>\n%s\n<Else>\n%s" % (o.condition,
167-
then_body, else_body)
173+
return self.indent + f"<If {o.condition}>\n{then_body}\n<Else>\n{else_body}"
168174
else:
169-
return self.indent + "<If %s>\n%s" % (o.condition, then_body)
175+
return self.indent + f"<If {o.condition}>\n{then_body}"
170176

171177

172178
class CGen(Visitor):
@@ -249,20 +255,20 @@ def _gen_value(self, obj, mode=1, masked=()):
249255

250256
if (obj._mem_stack or obj._mem_constant) and mode == 1:
251257
strtype = self.ccode(obj._C_typedata)
252-
strshape = ''.join('[%s]' % self.ccode(i) for i in obj.symbolic_shape)
258+
strshape = ''.join(f'[{self.ccode(i)}]' for i in obj.symbolic_shape)
253259
else:
254260
strtype = self.ccode(obj._C_ctype)
255261
strshape = ''
256262
if isinstance(obj, (AbstractFunction, IndexedData)) and mode >= 1:
257263
if not obj._mem_stack:
258-
strtype = '%s%s' % (strtype, self._restrict_keyword)
264+
strtype = f'{strtype}{self._restrict_keyword}'
259265
strtype = ' '.join(qualifiers + [strtype])
260266

261267
if obj.is_LocalObject and obj._C_modifier is not None and mode == 2:
262268
strtype += obj._C_modifier
263269

264270
strname = obj._C_name
265-
strobj = '%s%s' % (strname, strshape)
271+
strobj = f'{strname}{strshape}'
266272

267273
if obj.is_LocalObject and obj.cargs and mode == 1:
268274
arguments = [self.ccode(i) for i in obj.cargs]
@@ -396,16 +402,16 @@ def visit_PointerCast(self, o):
396402

397403
if f.is_PointerArray:
398404
# lvalue
399-
lvalue = c.Value(cstr, '**%s' % f.name)
405+
lvalue = c.Value(cstr, f'**{f.name}')
400406

401407
# rvalue
402408
if isinstance(o.obj, ArrayObject):
403-
v = '%s->%s' % (o.obj.name, f._C_name)
409+
v = f'{o.obj.name}->{f._C_name}'
404410
elif isinstance(o.obj, IndexedData):
405411
v = f._C_name
406412
else:
407413
assert False
408-
rvalue = '(%s**) %s' % (cstr, v)
414+
rvalue = f'({cstr}**) {v}'
409415

410416
else:
411417
# lvalue
@@ -414,12 +420,12 @@ def visit_PointerCast(self, o):
414420
else:
415421
v = f.name
416422
if o.flat is None:
417-
shape = ''.join("[%s]" % self.ccode(i) for i in o.castshape)
418-
rshape = '(*)%s' % shape
423+
shape = ''.join(f"[{self.ccode(i)}]" for i in o.castshape)
424+
rshape = f'(*){shape}'
419425
lvalue = c.Value(cstr, f'(*{self._restrict_keyword} {v}){shape}')
420426
else:
421427
rshape = '*'
422-
lvalue = c.Value(cstr, '*%s' % v)
428+
lvalue = c.Value(cstr, f'*{v}')
423429
if o.alignment and f._data_alignment:
424430
lvalue = c.AlignedAttribute(f._data_alignment, lvalue)
425431

@@ -432,14 +438,14 @@ def visit_PointerCast(self, o):
432438
else:
433439
assert False
434440

435-
rvalue = '(%s %s) %s->%s' % (cstr, rshape, f._C_name, v)
441+
rvalue = f'({cstr} {rshape}) {f._C_name}->{v}'
436442
else:
437443
if isinstance(o.obj, Pointer):
438444
v = o.obj.name
439445
else:
440446
v = f._C_name
441447

442-
rvalue = '(%s %s) %s' % (cstr, rshape, v)
448+
rvalue = f'({cstr} {rshape}) {v}'
443449

444450
return c.Initializer(lvalue, rvalue)
445451

@@ -449,17 +455,19 @@ def visit_Dereference(self, o):
449455
i = a1.indexed
450456
cstr = self.ccode(i._C_typedata)
451457
if o.flat is None:
452-
shape = ''.join("[%s]" % self.ccode(i) for i in a0.symbolic_shape[1:])
453-
rvalue = '(%s (*)%s) %s[%s]' % (cstr, shape, a1.name,
454-
a1.dim.name)
458+
shape = ''.join(f"[{self.ccode(i)}]" for i in a0.symbolic_shape[1:])
459+
rvalue = f'({cstr} (*){shape}) {a1.name}[{a1.dim.name}]'
455460
lvalue = c.Value(cstr, f'(*{self._restrict_keyword} {a0.name}){shape}')
456461
else:
457-
rvalue = '(%s *) %s[%s]' % (cstr, a1.name, a1.dim.name)
462+
rvalue = f'({cstr} *) {a1.name}[{a1.dim.name}]'
458463
lvalue = c.Value(cstr, f'*{self._restrict_keyword} {a0.name}')
459464
if a0._data_alignment:
460465
lvalue = c.AlignedAttribute(a0._data_alignment, lvalue)
461466
else:
462-
rvalue = '*%s' % a1.name if a1.is_Symbol else '%s->%s' % (a1.name, a0._C_name)
467+
if a1.is_Symbol:
468+
rvalue = f'*{a1.name}'
469+
else:
470+
rvalue = f'{a1.name}->{a0._C_name}'
463471
lvalue = self._gen_value(a0, 0)
464472
return c.Initializer(lvalue, rvalue)
465473

@@ -504,7 +512,7 @@ def visit_Expression(self, o):
504512
def visit_AugmentedExpression(self, o):
505513
c_lhs = self.ccode(o.expr.lhs, dtype=o.dtype)
506514
c_rhs = self.ccode(o.expr.rhs, dtype=o.dtype)
507-
code = c.Statement("%s %s= %s" % (c_lhs, o.op, c_rhs))
515+
code = c.Statement(f"{c_lhs} {o.op}= {c_rhs}")
508516
if o.pragmas:
509517
code = c.Module(self._visit(o.pragmas) + (code,))
510518
return code
@@ -548,23 +556,23 @@ def visit_Iteration(self, o):
548556

549557
# For backward direction flip loop bounds
550558
if o.direction == Backward:
551-
loop_init = 'int %s = %s' % (o.index, self.ccode(_max))
552-
loop_cond = '%s >= %s' % (o.index, self.ccode(_min))
553-
loop_inc = '%s -= %s' % (o.index, o.limits[2])
559+
loop_init = f'int {o.index} = {self.ccode(_max)}'
560+
loop_cond = f'{o.index} >= {self.ccode(_min)}'
561+
loop_inc = f'{o.index} -= {o.limits[2]}'
554562
else:
555-
loop_init = 'int %s = %s' % (o.index, self.ccode(_min))
556-
loop_cond = '%s <= %s' % (o.index, self.ccode(_max))
557-
loop_inc = '%s += %s' % (o.index, o.limits[2])
563+
loop_init = f'int {o.index} = {self.ccode(_min)}'
564+
loop_cond = f'{o.index} <= {self.ccode(_max)}'
565+
loop_inc = f'{o.index} += {o.limits[2]}'
558566

559567
# Append unbounded indices, if any
560568
if o.uindices:
561-
uinit = ['%s = %s' % (i.name, self.ccode(i.symbolic_min)) for i in o.uindices]
569+
uinit = [f'{i.name} = {self.ccode(i.symbolic_min)}' for i in o.uindices]
562570
loop_init = c.Line(', '.join([loop_init] + uinit))
563571

564572
ustep = []
565573
for i in o.uindices:
566574
op = '=' if i.is_Modulo else '+='
567-
ustep.append('%s %s %s' % (i.name, op, self.ccode(i.symbolic_incr)))
575+
ustep.append(f'{i.name} {op} {self.ccode(i.symbolic_incr)}')
568576
loop_inc = c.Line(', '.join([loop_inc] + ustep))
569577

570578
# Create For header+body
@@ -587,7 +595,7 @@ def visit_While(self, o):
587595
return c.While(condition, c.Block(body))
588596
else:
589597
# Hack: cgen doesn't support body-less while-loops, i.e. `while(...);`
590-
return c.Statement('while(%s)' % condition)
598+
return c.Statement(f'while({condition})')
591599

592600
def visit_Callable(self, o):
593601
body = flatten(self._visit(i) for i in o.children)
@@ -607,7 +615,7 @@ def visit_MultiTraversable(self, o):
607615
return c.Collection(body)
608616

609617
def visit_UsingNamespace(self, o):
610-
return c.Statement('using namespace %s' % str(o.namespace))
618+
return c.Statement(f'using namespace {str(o.namespace)}')
611619

612620
def visit_Lambda(self, o):
613621
body = []
@@ -625,9 +633,11 @@ def visit_Lambda(self, o):
625633
extra.append(' '.join(str(i) for i in o.special))
626634
if o.attributes:
627635
extra.append(' ')
628-
extra.append(' '.join('[[%s]]' % i for i in o.attributes))
629-
top = c.Line('[%s](%s)%s' %
630-
(', '.join(captures), ', '.join(decls), ''.join(extra)))
636+
extra.append(' '.join(f'[[{i}]]' for i in o.attributes))
637+
ccapt = ', '.join(captures)
638+
cdecls = ', '.join(decls)
639+
cextra = ''.join(extra)
640+
top = c.Line(f'[{ccapt}]({cdecls}){cextra}')
631641
return LambdaCollection([top, c.Block(body)])
632642

633643
def visit_HaloSpot(self, o):
@@ -636,7 +646,8 @@ def visit_HaloSpot(self, o):
636646

637647
def visit_KernelLaunch(self, o):
638648
if o.templates:
639-
templates = '<%s>' % ','.join([str(i) for i in o.templates])
649+
ctemplates = ','.join([str(i) for i in o.templates])
650+
templates = f'<{ctemplates}>'
640651
else:
641652
templates = ''
642653

@@ -650,8 +661,7 @@ def visit_KernelLaunch(self, o):
650661
arguments = self._args_call(o.arguments)
651662
arguments = ','.join(arguments)
652663

653-
return c.Statement('%s%s<<<%s>>>(%s)'
654-
% (o.name, templates, launch_config, arguments))
664+
return c.Statement(f'{o.name}{templates}<<<{launch_config}>>>({arguments})')
655665

656666
# Operator-handle machinery
657667

@@ -752,7 +762,7 @@ class CInterface(CGen):
752762

753763
def _operator_includes(self, o):
754764
includes = super()._operator_includes(o)
755-
includes.append(c.Include("%s.h" % o.name, system=False))
765+
includes.append(c.Include(f"{o.name}.h", system=False))
756766

757767
return includes
758768

@@ -764,7 +774,7 @@ def visit_Operator(self, o):
764774
typedecls = self._operator_typedecls(o, mode='public')
765775
guarded_typedecls = []
766776
for i in typedecls:
767-
guard = "DEVITO_%s" % i.tpname.upper()
777+
guard = f"DEVITO_{i.tpname.upper()}"
768778
iflines = [c.Define(guard, ""), blankline, i, blankline]
769779
guarded_typedecl = c.IfNDef(guard, iflines, [])
770780
guarded_typedecls.extend([guarded_typedecl, blankline])
@@ -1393,13 +1403,15 @@ def __init__(self, name, arguments, is_expr=False, is_indirect=False,
13931403

13941404
def generate(self):
13951405
if self.templates:
1396-
tip = "%s<%s>" % (self.name, ", ".join(str(i) for i in self.templates))
1406+
ctemplates = ", ".join(str(i) for i in self.templates)
1407+
tip = f"{self.name}<{ctemplates}>"
13971408
else:
13981409
tip = self.name
13991410
if not self.is_indirect:
1400-
tip = "%s(" % tip
1411+
tip = f"{tip}("
14011412
else:
1402-
tip = "%s%s" % (tip, ',' if self.arguments else '')
1413+
cargs = ',' if self.arguments else ''
1414+
tip = f"{tip}{cargs}"
14031415
processed = []
14041416
for i in self.arguments:
14051417
if isinstance(i, (MultilineCall, LambdaCollection)):
@@ -1421,7 +1433,7 @@ def generate(self):
14211433
if not self.is_expr:
14221434
tip += ";"
14231435
if self.cast:
1424-
tip = '(%s)%s' % (self.cast, tip)
1436+
tip = f'({self.cast}){tip}'
14251437
yield tip
14261438

14271439

0 commit comments

Comments
 (0)