-# Copyright (C) 2012 Team tiramisu (see AUTHORS for all contributors)
+# Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the whole pypy projet is under MIT licence
# ____________________________________________________________
"enables us to carry out a calculation and return an option's value"
-from tiramisu.error import (PropertiesOptionError, ConflictConfigError,
- NoValueReturned)
+from tiramisu.error import PropertiesOptionError, ConfigError
+from tiramisu.setting import multitypes
+from tiramisu.i18n import _
# ____________________________________________________________
-# automatic Option object
-#def special_owner_factory(name, owner, value,
-# callback, callback_params=None, config=None):
-# # in case of an 'auto' and a 'fill' without a value,
-# # we have to carry out a calculation
-# return calc_factory(name, callback, callback_params, config)
-def carry_out_calculation(name, callback, callback_params, config):
- # FIXME we have to know the exact status of the config
- # not to disrupt it
- # config.freeze()
- if callback_params is None:
- callback_params = {}
+
+
+def carry_out_calculation(option, config, callback, callback_params,
+ index=None, max_len=None):
+ """a function that carries out a calculation for an option's value
+
+ :param name: the option name (`opt.impl_getname()`)
+ :param name: the option
+ :param config: the context config in order to have
+ the whole options available
+ :param callback: the name of the callback function
+ :type callback: str
+ :param callback_params: the callback's parameters
+ (only keyword parameters are allowed)
+ :type callback_params: dict
+ :param index: if an option is multi, only calculates the nth value
+ :type index: int
+ :param max_len: max length for a multi
+ :type max_len: int
+
+ The callback_params is a dict. Key is used to build args (if key is '')
+ and kwargs (otherwise). Values are tuple of:
+ - values
+ - tuple with option and boolean's force_permissive (True when don't raise
+ if PropertiesOptionError)
+ Values could have multiple values only when key is ''.
+
+ * if no callback_params:
+ => calculate(<function func at 0x2092320>, [], {})
+
+ * if callback_params={'': ('yes',)}
+ => calculate(<function func at 0x2092320>, ['yes'], {})
+
+ * if callback_params={'value': ('yes',)}
+ => calculate(<function func at 0x165b320>, [], {'value': 'yes'})
+
+ * if callback_params={'': ('yes', 'no')}
+ => calculate('yes', 'no')
+
+ * if callback_params={'value': ('yes', 'no')}
+ => ValueError()
+
+ * if callback_params={'': (['yes', 'no'],)}
+ => calculate(<function func at 0x176b320>, ['yes', 'no'], {})
+
+ * if callback_params={'value': ('yes', 'no')}
+ => raises ValueError()
+
+ * if callback_params={'': ((opt1, False),)}
+
+ - a simple option:
+ opt1 == 11
+ => calculate(<function func at 0x1cea320>, [11], {})
+
+ - a multi option and not master/slave:
+ opt1 == [1, 2, 3]
+ => calculate(<function func at 0x223c320>, [[1, 2, 3]], {})
+
+ - option is master or slave of opt1:
+ opt1 == [1, 2, 3]
+ => calculate(<function func at 0x223c320>, [1], {})
+ => calculate(<function func at 0x223c320>, [2], {})
+ => calculate(<function func at 0x223c320>, [3], {})
+
+ - opt is a master or slave but not related to option:
+ opt1 == [1, 2, 3]
+ => calculate(<function func at 0x11b0320>, [[1, 2, 3]], {})
+
+ * if callback_params={'value': ((opt1, False),)}
+
+ - a simple option:
+ opt1 == 11
+ => calculate(<function func at 0x17ff320>, [], {'value': 11})
+
+ - a multi option:
+ opt1 == [1, 2, 3]
+ => calculate(<function func at 0x1262320>, [], {'value': [1, 2, 3]})
+
+ * if callback_params={'': ((opt1, False), (opt2, False))}
+
+ - two single options
+ opt1 = 11
+ opt2 = 12
+ => calculate(<function func at 0x217a320>, [11, 12], {})
+
+ - a multi option with a simple option
+ opt1 == [1, 2, 3]
+ opt2 == 12
+ => calculate(<function func at 0x2153320>, [[1, 2, 3], 12], {})
+
+ - a multi option with an other multi option but with same length
+ opt1 == [1, 2, 3]
+ opt2 == [11, 12, 13]
+ => calculate(<function func at 0x1981320>, [[1, 2, 3], [11, 12, 13]], {})
+
+ - a multi option with an other multi option but with different length
+ opt1 == [1, 2, 3]
+ opt2 == [11, 12]
+ => calculate(<function func at 0x2384320>, [[1, 2, 3], [11, 12]], {})
+
+ - a multi option without value with a simple option
+ opt1 == []
+ opt2 == 11
+ => calculate(<function func at 0xb65320>, [[], 12], {})
+
+ * if callback_params={'value': ((opt1, False), (opt2, False))}
+ => raises ValueError()
+
+ If index is not None, return a value, otherwise return:
+
+ * a list if one parameters have multi option
+ * a value otherwise
+
+ If calculate return list, this list is extend to return value.
+ """
tcparams = {}
+ # if callback_params has a callback, launch several time calculate()
one_is_multi = False
- len_multi = 0
- for key, value in callback_params.items():
- if type(value) == tuple:
- path, check_disabled = value
- try:
- opt_value = getattr(config, path)
- opt = config.unwrap_from_path(path)
- except PropertiesOptionError, e:
- if chek_disabled:
- continue
- raise PropertiesOptionError(e)
- is_multi = opt.is_multi()
- if is_multi:
- if opt_value != None:
- len_value = len(opt_value)
- if len_multi != 0 and len_multi != len_value:
- raise ConflictConfigError('unable to carry out a calculation, '
- 'option values with multi types must have same length for: '
- + name)
- len_multi = len_value
- one_is_multi = True
- tcparams[key] = (opt_value, is_multi)
- else:
- tcparams[key] = (value, False)
+ # multi's option should have same value for all option
+ len_multi = None
+ for callbacks in callback_params:
+ key = callbacks.name
+ for callbk in callbacks.params:
+ if callbk.option is not None:
+ # callbk is something link (opt, True|False)
+ opt = callbk.get_option(config)
+ force_permissive = callbk.force_permissive
+ path = config.cfgimpl_get_description().impl_get_path_by_opt(
+ opt)
+ # get value
+ try:
+ value = config._getattr(path, force_permissive=True)
+ except PropertiesOptionError as err:
+ if force_permissive:
+ continue
+ raise ConfigError(_('unable to carry out a calculation, '
+ 'option {0} has properties: {1} for: '
+ '{2}').format(option.impl_getname(),
+ err.proptype,
+ option._name))
+ is_multi = False
+ if opt.impl_is_multi():
+ #opt is master, search if option is a slave
+ if opt.impl_get_multitype() == multitypes.master:
+ if option in opt.impl_get_master_slaves():
+ is_multi = True
+ #opt is slave, search if option is an other slaves
+ elif opt.impl_get_multitype() == multitypes.slave:
+ if option in opt.impl_get_master_slaves().impl_get_master_slaves():
+ is_multi = True
+ if is_multi:
+ len_multi = len(value)
+ one_is_multi = True
+ tcparams.setdefault(key, []).append((value, is_multi))
+ else:
+ # callbk is a value and not a multi
+ tcparams.setdefault(key, []).append((callbk.value, False))
+
+ # if one value is a multi, launch several time calculate
+ # if index is set, return a value
+ # if no index, return a list
if one_is_multi:
ret = []
- for incr in range(len_multi):
- tcp = {}
- for key, couple in tcparams.items():
- value, ismulti = couple
- if ismulti and value != None:
- if key == '':
- params.append(value[incr])
+ if index:
+ range_ = [index]
+ else:
+ range_ = range(len_multi)
+ for incr in range_:
+ args = []
+ kwargs = {}
+ for key, couples in tcparams.items():
+ for couple in couples:
+ value, ismulti = couple
+ if ismulti:
+ val = value[incr]
else:
- tcp[key] = value[incr]
- else:
+ val = value
if key == '':
- params.append(value)
+ args.append(val)
else:
- tcp[key] = value
- ret.append(calculate(name, callback, tcp))
+ kwargs[key] = val
+ calc = calculate(callback, args, kwargs)
+ if index:
+ ret = calc
+ else:
+ ret.append(calc)
return ret
else:
- tcp = {}
- params = []
- for key, couple in tcparams.items():
- if key == '':
- params.append(couple[0])
- else:
- tcp[key] = couple[0]
- return calculate(name, callback, params, tcp)
-
-def calculate(name, callback, params, tcparams):
- try:
- # XXX not only creole...
- from creole import eosfunc
- return getattr(eosfunc, callback)(*params, **tcparams)
- except NoValueReturned, err:
- return ""
- except AttributeError, err:
- import traceback
- traceback.print_exc()
- raise ConflictConfigError("callback: {0} return error {1} for "
- "option: {2}".format(callback, str(err), name))
+ # no value is multi
+ # return a single value
+ args = []
+ kwargs = {}
+ for key, couples in tcparams.items():
+ for couple in couples:
+ # couple[1] (ismulti) is always False
+ if key == '':
+ args.append(couple[0])
+ else:
+ kwargs[key] = couple[0]
+ ret = calculate(callback, args, kwargs)
+ if callback_params != {}:
+ if isinstance(ret, list) and max_len:
+ ret = ret[:max_len]
+ if len(ret) < max_len:
+ ret = ret + [None] * (max_len - len(ret))
+ if isinstance(ret, list) and index:
+ if len(ret) < index + 1:
+ ret = None
+ else:
+ ret = ret[index]
+ return ret
+
+
+def calculate(callback, args, kwargs):
+ """wrapper that launches the 'callback'
+
+ :param callback: callback function
+ :param args: in the callback's arity, the unnamed parameters
+ :param kwargs: in the callback's arity, the named parameters
+ """
+ return callback(*args, **kwargs)