Skip to content

Commit ee6f9ac

Browse files
committed
feat(sugar): implMethod/Magic sup defval
1 parent fc7e57f commit ee6f9ac

4 files changed

Lines changed: 102 additions & 29 deletions

File tree

‎Objects/dictobjectImpl.nim‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,5 @@ proc PyDict_FromKeys*(cls: PyObject, iterable, value: PyObject): PyObject =
138138
retIfExc PyObject_SetItem(d, key, value)
139139
d
140140

141-
implDictMethod fromkeys(*a), [classmethod]:
142-
var
143-
iterable: PyObject
144-
value = pyNone
145-
PyArg_UnpackTuple("fromkeys", a, 1, 2, iterable, value)
141+
implDictMethod fromkeys(iterable: PyObject, value = PyObject pyNone), [classmethod]:
146142
PyDict_FromKeys(selfNoCast, iterable, value)

‎Objects/pyobject.nim‎

Lines changed: 85 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -289,21 +289,29 @@ template noKw(name){.dirty.} =
289289
#TODO:rec-dep
290290
else: {.error: "please import Objects/bltcommon".}
291291

292+
proc countDefval(argTypes: NimNode): int =
293+
for child in argTypes:
294+
if child.kind == nnkExprEqExpr:
295+
result.inc
296+
292297
macro checkArgTypes*(nameAndArg, code: untyped): untyped =
293298
let methodName = nameAndArg[0]
294299
var argTypes = nameAndArg[1]
295300
let body = newStmtList()
296-
let argNum = argTypes.len # origin py params len
301+
let argNum = argTypes.len # origin py total params len,
302+
# including *args/**kwargs, and those with defval
303+
var posArgNum = argNum # positional only arg num
297304
let oriParams = code.params # origin nim params
298305

299306
var oriLastIsKw: bool
300-
let oriMultiArg = oriParams.paramsLastSeqObjectOrWithDict oriLastIsKw
307+
let oriSupMultiArg = oriParams.paramsLastSeqObjectOrWithDict oriLastIsKw
301308
var varargId, kwargId: NimNode
302309
var vargs: NimNode # args or kwargs
303310

304311
template popNameTo(res) =
305312
res = vargs[1]
306313
argTypes.del(argTypes.len-1, 1)
314+
posArgNum.dec
307315
if argNum > 0 and (vargs = argTypes.last; vargs.kind == nnkPrefix):
308316
case vargs[0].strVal
309317
of "*": popNameTo varargId
@@ -319,19 +327,26 @@ macro checkArgTypes*(nameAndArg, code: untyped): untyped =
319327
elif oriLastIsKw:
320328
body.add getAst noKw $methodName
321329
if not varargId.isNil:
322-
if not oriMultiArg:
330+
if not oriSupMultiArg:
323331
error "varargs is not allowed for this kind of functions", code
324-
if oriMultiArg:
332+
let nDefval = countDefval(argTypes)
333+
posArgNum.dec nDefval
334+
if oriSupMultiArg:
335+
let methodNameStrNode = newStrLitNode($methodName)
336+
let posNode = newIntLitNode(posArgNum)
325337
if varargId.isNil:
326338
# return `checkArgNum(1, "append")` like
327-
body.add newCall(ident("checkArgNum"),
328-
newIntLitNode(argNum),
329-
newStrLitNode($methodName)
330-
)
339+
let call = newCall("checkArgNum", posNode,)
340+
if nDefval > 0:
341+
call.add newIntLitNode(posArgNum + nDefval)
342+
call.add methodNameStrNode
343+
344+
body.add call
331345
else:
346+
posArgNum.dec
332347
body.add newCall(ident("checkArgNumAtLeast"),
333-
newIntLitNode(argNum - 1),
334-
newStrLitNode($methodName)
348+
posNode,
349+
methodNameStrNode
335350
)
336351
let remainingArgNode = varargId
337352
let nowNum = argTypes.len
@@ -341,7 +356,15 @@ macro checkArgTypes*(nameAndArg, code: untyped): untyped =
341356

342357
template addLetDecl(name, value) =
343358
discard body.add newLetStmt(name, value)
344-
let toUnpackVargs = oriMultiArg
359+
360+
let toUnpackVargs = oriSupMultiArg
361+
var vararg_len: NimNode
362+
if toUnpackVargs:
363+
vararg_len = genSym(nskLet, "vararg_len")
364+
body.add newLetStmt(
365+
vararg_len,
366+
newCall("len", ident("args"))
367+
)
345368
for idx, child in argTypes:
346369
let obj =
347370
if toUnpackVargs:
@@ -360,16 +383,60 @@ macro checkArgTypes*(nameAndArg, code: untyped): untyped =
360383
error "only *args, **kwargs is allowed (and each no more than one)", child
361384
else:
362385
let name = child[0]
363-
let tp = child[1]
364-
if tp.strVal == "PyObject": # won't bother checking
386+
var tp: NimNode
387+
var defval: NimNode
388+
var hasDefVal = false
389+
if child.kind == nnkExprColonExpr:
390+
tp = child[1]
391+
else:
392+
#TODO: handle startPosOnly, startKwOnly
393+
expectKind child, nnkExprEqExpr
394+
hasDefVal = true
395+
defval = child[1]
396+
if hasDefVal:
397+
posArgNum.dec
398+
if not hasDefVal and tp.strVal == "PyObject": # won't bother checking
365399
addLetDecl(name, obj)
366400
else:
367-
let tpObj = ident(objName2tpObjName(tp.strVal))
368401
let methodNameStrNode = newStrLitNode(methodName.strVal)
369-
body.add(getAst(checkTypeTmpl(obj, tp, tpObj, methodNameStrNode)))
370-
body.add(quote do:
371-
let `name` = `tp`(`obj`)
372-
)
402+
if not hasDefVal and tp.strVal[0] == 'P':
403+
# if is a PyObject subtype
404+
#XXX: very hacky way to detect PyObject subtype
405+
let tpObj = ident(objName2tpObjName(tp.strVal))
406+
body.add(getAst(checkTypeTmpl(obj, tp, tpObj, methodNameStrNode)))
407+
body.add(quote do:
408+
let `name` = `tp`(`obj`)
409+
)
410+
else:
411+
let stmtInBlk = newStmtList()
412+
let tmp = genSym(nskVar, "tmpvar")
413+
stmtInBlk.add if hasDefVal:
414+
newVarStmt(tmp, defval)
415+
else:
416+
quote do:
417+
var `tmp`: `tp`
418+
template asgnTmpNode: untyped{.dirty.} = quote do: `tmp` = `obj`
419+
let tovalExpr =
420+
if defval.kind == nnkCommand and defval.last.kind == nnkNilLit and
421+
defval[0].strVal == "PyObject":
422+
# default value is `nil`, so we need not check arg num
423+
asgnTmpNode
424+
else:
425+
quote do: retIfExc toval(`obj`, `tmp`)
426+
stmtInBlk.add if not toUnpackVargs: tovalExpr
427+
else:
428+
let outRng = if hasDefVal:
429+
quote do: `tmp` = `defval`
430+
else:
431+
quote do: errArgNum(`idx`, `posArgNum`, `methodNameStrNode`)
432+
#TODO:compile: optimize redundant check when compiling
433+
quote do:
434+
if `idx` < `vararg_len`:
435+
`tovalExpr`
436+
else:
437+
`outRng`
438+
stmtInBlk.add tmp # the last expr is the value
439+
body.add newLetStmt(name, newBlockStmt(stmtInBlk))
373440
body.add code.body
374441
code.body = body
375442
code

‎Python/getargs/vargs.nim‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ proc PyArg_VaUnpackTuple(name: NimNode; args: NimNode#[openArray[PyObject]]#; mi
5757
PyArg_DoTupleImpl asgn
5858

5959
proc PyArg_VaParseTuple*(name: NimNode; args: NimNode#[openArray[PyObject]]#; min, max: Natural;
60-
vargs: NimNode#[varargs[PyObject]]#,
60+
vargs: NimNode#[varargs[auto]]#,
6161
): NimNode =
6262
#TODO: current this expr is void, using `retIfExc` to `return` exception, change to become an expr
6363
template asgn(v, args, i): untyped =
@@ -75,6 +75,11 @@ template PyArg_UnpackTuple*(name; args: openArray[PyObject]; min, max: Natural;
7575
bind unpack_stack
7676
unpack_stack(name, args, min, max, vargs)
7777

78+
macro PyArg_ParseTuple*(name: string; args: openArray[PyObject], min, max: static Natural;
79+
vargs: varargs[typed],
80+
) =
81+
PyArg_VaParseTuple(name, args, min, max, vargs)
82+
7883
template PyArg_UnpackTuple*(name; args: PyTupleObject, min, max: Natural;
7984
vargs: varargs[PyObject],
8085
) =

‎Python/sysmodule.nim‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ import ../Objects/[
99
noneobject,
1010
typeobject,
1111
]
12+
1213
import ../Objects/exceptions/extra_utils
13-
import ../Objects/numobjects/intobject_decl
14+
import ../Objects/numobjects/[intobject_decl, numobjects_comm]
1415
import ../Objects/bltcommon; export bltcommon
1516
import ../Utils/trans_imp
16-
import ./getargs/[va_and_kw, dispatch]
17+
from ./neval_frame import privateGetframeNoAudit
18+
import ./getargs/[vargs, va_and_kw, dispatch]
1719
impExp sysmodule,
1820
decl, init, audit, hooks, attrs, int_max_str_digits
1921

@@ -32,8 +34,7 @@ implSysModuleMethod excepthook(exctype: PyTypeObject, value: PyBaseErrorObject,
3234
implSysModuleMethod displayhook(x): displayhook(x)
3335

3436
implSysModuleMethod get_int_max_str_digits(): newPyInt PySys_GetIntMaxStrDigits()
35-
implSysModuleMethod set_int_max_str_digits(*a, **kw):
36-
retIfExc PyArg_ParseTupleAndKeywordsAs("set_int_max_str_digits", a, kw, [], maxdigits: int)
37+
implSysModuleMethod set_int_max_str_digits(maxdigits: int):
3738
retIfExc PySys_SetIntMaxStrDigits(maxdigits)
3839
pyNone
3940

@@ -43,4 +44,8 @@ proc exit*(status: PyObject = pyNone): PyObject{.clinicGenWithPrefix"sys".} =
4344
res.thrown = true
4445
return res
4546

46-
implSysModuleMethod exit(*args): sys_exit(args, nil)
47+
implSysModuleMethod "_getframe"(depth = 0):
48+
result = privateGetframeNoAudit(depth)
49+
retIfExc audit("sys._getframe", result)
50+
51+
implSysModuleMethod exit(exitcode = PyObject pyIntZero): sysmodule.exit(exitcode)

0 commit comments

Comments
 (0)