示例#1
0
def eval_statement_SetNameFvalue(r, context):
    check_isinstance(r, CDP.SetNameFValue)
    name = r.name.value
    right_side = r.right_side

    if name in context.constants:
        msg = 'Constant %r already set.' % name
        raise DPSemanticError(msg, where=r.where)

    if name in context.var2resource:
        msg = 'Resource %r already set.' % name
        raise DPSemanticError(msg, where=r.where)

    if name in context.var2function:
        msg = 'Name %r already used.' % name
        raise DPSemanticError(msg, where=r.where)

    from .eval_lfunction_imp import eval_lfunction

    fv = eval_lfunction(right_side, context)

    ndp = context.names[fv.dp]
    # TODO: check that is not used anywhere

    current = fv.s
    updated = name
    try:
        ndp2 = ndp_rename_function(ndp, current=current, updated=updated)
        context.names[fv.dp] = ndp2
        fv = CFunction(fv.dp, updated)
    except CouldNotRename:
        pass

    context.set_var2function(name, fv)
示例#2
0
def check_name_not_in_use(name, context, expr):
    if name in context.constants:
        msg = 'Constant %r already set.' % name
        raise DPSemanticError(msg, where=expr.where)

    if name in context.var2resource:
        msg = 'Resource %r already set.' % name
        raise DPSemanticError(msg, where=expr.where)

    if name in context.var2function:
        msg = 'Name %r already used.' % name
        raise DPSemanticError(msg, where=expr.where)
示例#3
0
    def make_function(self, dp, s):
        assert isinstance(dp, str)
        if not dp in self.names:
            msg = 'Unknown design problem %r.' % dp
            raise DPSemanticError(msg)

        ndp = self.names[dp]

        if not s in ndp.get_fnames():
            msg = 'Unknown function %r for design problem %r.' % (s, dp)
            msg += ' Known functions: %s.' % format_list(ndp.get_fnames())
            raise DPSemanticError(msg)

        return CFunction(dp, s)
示例#4
0
    def make_resource(self, dp, s):
        if not isinstance(dp, str):
            raise DPInternalError((dp, s))
        if not dp in self.names:
            msg = 'Unknown design problem %r.' % dp
            raise DPSemanticError(msg)

        ndp = self.names[dp]

        if not s in ndp.get_rnames():
            msg = 'Unknown resource %r for design problem %r.' % (s, dp)
            msg += ' Known functions: %s.' % format_list(ndp.get_rnames())
            raise DPSemanticError(msg)

        return CResource(dp, s)
示例#5
0
    def _load_hooks(self, load_arg, hooks, expected):
        errors = []
        if not hooks:
            msg = 'Could not load %r because no loading hooks provided.' % load_arg
            raise_desc(DPSemanticError, msg)
        for hook in hooks:
            try:
                try:
                    res = hook(load_arg, context=self)
                    if not isinstance(res, expected):
                        msg = 'The hook did not return the expected type.'
                        raise_desc(DPSemanticError,
                                   msg,
                                   res=res,
                                   expected=expected)
                    return res
                except TypeError:
                    msg = 'Could not use hook %r' % hook
                    logger.error(msg)
                    raise
            except DPSemanticError as e:
                if len(hooks) == 1:
                    raise
                else:
                    errors.append(e)

        s = "\n\n".join(map(str, errors))
        msg = 'Could not load %r: \n%s' % (load_arg, s)
        raise DPSemanticError(msg)
示例#6
0
def eval_constant_VariableRef(op, context):
    if op.name in context.constants:
        return context.constants[op.name]

    if op.name in context.var2resource:
        res = context.var2resource[op.name]
        msg = 'This is a resource, not a constant.'
        raise_desc(NotConstant, msg, res=res)

    if op.name in context.var2function:  # XXX: not sure this is needed
        res = context.var2function[op.name]
        msg = 'This is a function, not a constant.'
        raise_desc(NotConstant, msg, res=res)

    try:
        x = context.get_ndp_fun(op.name)
    except ValueError:
        pass
    else:
        msg = 'Corresponds to new function, not a constant.'
        raise_desc(NotConstant, msg, x=x)

    try:
        x = context.get_ndp_res(op.name)
    except ValueError:
        pass
    else:
        msg = 'Corresponds to new resource, not a constant.'
        raise_desc(NotConstant, msg, x=x)

    msg = 'Variable ref %r unknown.' % op.name
    raise DPSemanticError(msg, where=op.where)
示例#7
0
文件: refinement.py 项目: afcarl/mcdp
        def visit_to_check2(x):
#             print('  visit_to_check2(%s)  %s %s' % (nt_string(x), type(x).__name__, x))
            if isinstance(x, CDP.Resource):
                l = x.dp.value + '.' + x.s.value
                Flavors.rvalue.add(l)
            elif isinstance(x, CDP.Function):
                l = x.dp.value + '.' + x.s.value
                Flavors.fvalue.add(l) 
            elif isinstance(x, CDP.VName):
                Flavors.either.add(x.value)
            elif isinstance(x, CDP.VariableRef):
                if x.name in functions and x.name in resources:
                    # ambiguous
                    Flavors.either.add(x.name) # not other flavor  
                elif x.name in functions or x.name in deriv_resources:
#                     print('%r contributes to Flavors.rvalue' % x.name)
                    Flavors.rvalue.add(x.name) # not other flavor
                elif x.name in resources or x.name in deriv_functions:
#                     print('%r contributes to Flavors.fvalue' % x.name)
                    Flavors.fvalue.add(x.name) # not other flavor
                elif x.name in variables:
#                     print('%r contributes to Flavors.either' % x.name)
                    Flavors.either.add(x.name)  
                elif si.is_constant(x.name):
#                     print('%r constant contributes to Flavors.either' % x.name)
                    Flavors.either.add(x.name)  
                else:
                    msg = 'Could not resolve reference to %r.' % x.name
                    raise DPSemanticError(msg, where=x.where)
示例#8
0
    def bb(tokens, loc, s):
        where = Where(s, loc)
        try:
            try:
                res = b(tokens)
            except TypeError as e:
                ttokens = list(tokens)
                s = "\n".join("- %s " % str(x) for x in ttokens)
                msg = 'Cannot invoke %r\nwith %d tokens:\n%s.' % (
                    b, len(ttokens), s)
                raise_wrapped(TypeError, e, msg)
        except DPSyntaxError as e:
            if e.where is None:
                e.where = where
                raise DPSyntaxError(str(e), where=where)
            else:
                raise
        except DPSemanticError as e:
            if e.where is None:
                raise DPSemanticError(str(e), where=where)
            else:
                raise
        except BaseException as e:
            raise_wrapped(DPInternalError,
                          e,
                          "Error while parsing.",
                          where=where.__str__(),
                          tokens=tokens)

        if isnamedtupleinstance(res) and res.where is None:
            res = get_copy_with_where(res, where=where)

        return res
示例#9
0
def eval_lfunction_variableref(lf, context):

    if lf.name in context.constants:
        c = context.constants[lf.name]
        assert isinstance(c, ValueWithUnits)
        return get_valuewithunits_as_function(c, context)

    if lf.name in context.uncertain_constants:
        c = context.uncertain_constants[lf.name]
        assert isinstance(c, UncertainConstant)
        from .helpers import get_uncertainconstant_as_function
        return get_uncertainconstant_as_function(c, context)

    if lf.name in context.var2function:
        return context.var2function[lf.name]

    try:
        dummy_ndp = context.get_ndp_res(lf.name)
    except ValueError:
        msg = 'Function %r not declared.' % lf.name
        raise DPSemanticError(msg, where=lf.where)

    s = dummy_ndp.get_rnames()[0]

    msg = (
        'Please use the more precise form "required %s" rather than simply "%s".'
        % (lf.name, lf.name))
    warn_language(lf, MCDPWarnings.LANGUAGE_REFERENCE_OK_BUT_IMPRECISE, msg,
                  context)

    return context.make_function(get_name_for_res_node(lf.name), s)
示例#10
0
def eval_rvalue_VariableRef(rvalue, context):
    if rvalue.name in context.constants:
        c = context.constants[rvalue.name]
        assert isinstance(c, ValueWithUnits)
        return get_valuewithunits_as_resource(c, context)
        # return eval_rvalue(context.constants[rvalue.name], context)

    elif rvalue.name in context.var2resource:
        return context.var2resource[rvalue.name]

    try:
        dummy_ndp = context.get_ndp_fun(rvalue.name)
    except ValueError:  # as e:
        msg = 'Function %r not declared.' % rvalue.name

        if context.fnames:
            msg += ' Available: %s.' % ", ".join(context.fnames)
        else:
            msg += ' No function declared so far.'
        raise DPSemanticError(msg, where=rvalue.where)

    s = dummy_ndp.get_rnames()[0]
    
    msg = ('Please use the more precise form "provided %s" rather than simply "%s".'
           % (rvalue.name, rvalue.name))
    warn_language(rvalue, MCDPWarnings.LANGUAGE_REFERENCE_OK_BUT_IMPRECISE, msg, context)

    return context.make_resource(get_name_for_fun_node(rvalue.name), s)
示例#11
0
def eval_rvalue_DerivResourceRef(rvalue, context):
    check_isinstance(rvalue, CDP.DerivResourceRef)
    _ = rvalue.drname.value
    if _  in context.var2resource:
        return context.var2resource[_]
    else:
        msg = 'Derivative resource %r not found.' % _
        raise DPSemanticError(msg, where=rvalue.where) # or internal?
示例#12
0
def eval_lfunction_DerivFunctionRef(lf, context):
    check_isinstance(lf, CDP.DerivFunctionRef)
    _ = lf.dfname.value
    if _ in context.var2function:
        return context.var2function[_]
    else:
        msg = 'Derivative functionality %r not found.' % _
        raise DPSemanticError(msg, where=lf.where)
示例#13
0
def eval_lfunction_ActualVarRef(lf, context):
    check_isinstance(lf, CDP.ActualVarRef)
    _ = lf.vname.value
    if _ in context.var2function:
        return context.var2function[_]
    else:
        msg = 'Cannot resolve variable %r.' % _
        raise DPSemanticError(msg, where=lf.where)
示例#14
0
def add_function(fname, F, context, r, repeated_ok=False):
    check_isinstance(fname, str)
    try:
        check_good_name_for_function(fname)
    except ValueError as e:
        msg = 'Invalid name for functionality: %s' % e
        raise DPSemanticError(msg, where=r.where)

    if fname in context.fnames:
        if not repeated_ok:
            msg = 'Repeated function name %r.' % fname
            raise DPSemanticError(msg, where=r.where)
        else:
            # check same or different
            warnings.warn('check same')
    else:
        context.add_ndp_fun_node(fname, F)
    return context.make_resource(get_name_for_fun_node(fname), fname)
示例#15
0
def add_resource(rname, R, context, r, repeated_ok=False):
    check_isinstance(rname, str)
    try:
        check_good_name_for_resource(rname)
    except ValueError as e:
        msg = 'Invalid name for resource: %s' % e
        raise DPSemanticError(msg, where=r.where)

    if rname in context.rnames:
        if not repeated_ok:
            msg = 'Repeated resource name %r.' % rname
            raise DPSemanticError(msg, where=r.where)
        else:
            # check same or different
            warnings.warn('check same')
    else:
        context.add_ndp_res_node(rname, R)
    return context.make_function(get_name_for_res_node(rname), rname)
示例#16
0
def eval_rvalue_ActualVarRef(rvalue, context):
    check_isinstance(rvalue, CDP.ActualVarRef)

    _ = rvalue.vname.value
    if _  in context.var2resource:
        return context.var2resource[_]
    else:
        msg = 'Cannot resolve variable %r not found.' % _
        raise DPSemanticError(msg, where=rvalue.where) # or internal?
示例#17
0
def eval_constant_ConstantRef(rvalue, context):
    check_isinstance(rvalue, CDP.ConstantRef)
    _ = rvalue.cname.value
    if _ in context.constants:
        c = context.constants[_]
        assert isinstance(c, ValueWithUnits)
        return c
    else:
        msg = 'Constant value %r not found.' % _
        raise DPSemanticError(msg, where=rvalue.where)  # or internal?
示例#18
0
文件: refinement.py 项目: afcarl/mcdp
    def found_rname(rname):
        if isinstance(rname, CDP.Placeholder):
            return

        check_isinstance(rname, CDP.RName)
        _ = rname.value
        if _ in resources:
            msg = 'Repeated resource %r.' % _
            raise DPSemanticError(msg, where=rname.where)
        
        if _ in deriv_resources:
            msg = 'The name %r is already used.' % _
            raise DPSemanticError(msg, where=rname.where)

        if _ in variables:
            msg = 'The name %r is already used by a variable.' % _
            raise DPSemanticError(msg, where=rname.where)
            
        resources.add(rname.value) 
示例#19
0
文件: refinement.py 项目: afcarl/mcdp
    def found_fname(fname):
        if isinstance(fname, CDP.Placeholder):
            return
        check_isinstance(fname, CDP.FName)
        infer_debug('found fname: %s' % fname.value)
        _ = fname.value
        if _ in functions:
            msg = 'Repeated function %r.' % _
            raise DPSemanticError(msg, where=fname.where)
        
        if _ in deriv_resources:
            msg = 'The name %r is already used.' % _
            raise DPSemanticError(msg, where=fname.where)

        if _ in variables:
            msg = 'The name %r is already used by a variable.' % _
            raise DPSemanticError(msg, where=fname.where)

        functions.add(fname.value)
示例#20
0
def which_line(contents, fragment, after_line):
    lines = contents.split('\n')
    after = "\n".join(lines[after_line:])
    if not fragment in contents:
        msg = 'Cannot find fragment %r in file after line %d' % (fragment, after_line)
        msg += '\n' + indent(after, '| ')
        raise DPSemanticError(msg)
    i = after.index(fragment)
    line = len(after[:i].split('\n')) -1 
    return line + after_line
示例#21
0
def eval_lfunction_ConstantRef(lf, context):
    check_isinstance(lf, CDP.ConstantRef)
    _ = lf.cname.value
    if _ in context.constants:
        c = context.constants[_]
        assert isinstance(c, ValueWithUnits)
        return get_valuewithunits_as_function(c, context)
    else:
        msg = 'Cannot resolve constant %r.' % _
        raise DPSemanticError(msg, where=lf.where)
示例#22
0
 def get_rtype(self, a):
     """ Gets the type of a resource, raises DPSemanticError if not present. """
     check_isinstance(a, CResource)
     if not a.dp in self.names:
         msg = "Cannot find design problem %r." % str(a)
         raise DPSemanticError(msg)
     ndp = self.names[a.dp]
     if not a.s in ndp.get_rnames():
         msg = "Design problem %r does not have resource %r." % (a.dp, a.s)
         raise_desc(DPSemanticError, msg, rnames=ndp.get_rnames())
     return ndp.get_rtype(a.s)
示例#23
0
 def get_ftype(self, a):
     """ Gets the type of a function, raises DPSemanticError if not present. """
     check_isinstance(a, CFunction)
     if not a.dp in self.names:
         msg = "Cannot find design problem %r." % str(a)
         raise DPSemanticError(msg)
     dp = self.names[a.dp]
     if not a.s in dp.get_fnames():
         msg = "Design problem %r does not have function %r." % (a.dp, a.s)
         raise_desc(DPSemanticError, msg, fnames=dp.get_fnames())
     return dp.get_ftype(a.s)
示例#24
0
文件: eval_math.py 项目: rusi/mcdp
def eval_constant_divide(op, context):
    from .eval_constant_imp import eval_constant

    ops = get_odd_ops(unwrap_list(op.ops))
    if len(ops) != 2:
        raise DPSemanticError('divide by more than two')

    constants = [eval_constant(_, context) for _ in ops]

    factors = [constants[0], inv_constant(constants[1])]
    from .misc_math import generic_mult_constantsN
    return generic_mult_constantsN(factors)
示例#25
0
文件: misc_math.py 项目: rusi/mcdp
def inv_constant(a):
    if a.unit == Nat():
        raise DPNotImplementedError('division by natural number')
        warnings.warn('Please think more about this. Now 1/N -> 1.0/N')
        unit = Rcomp()
    else:
        unit = inv_unit(a.unit)

    if a.value == 0:
        raise DPSemanticError('Division by zero')
    # TODO: what about integers?
    value = 1.0 / a.value
    return ValueWithUnits(value=value, unit=unit)
示例#26
0
文件: misc_math.py 项目: rusi/mcdp
def plus_constants2_rcompunits(a, b):
    """ raises ConstantsNotCompatibleForAddition """
    check_isinstance(a.unit, RcompUnits)
    check_isinstance(b.unit, RcompUnits)
    R = a.unit
    Fs = [a.unit, b.unit]
    values = [a.value, b.value]
    try:
        res = sum_units(Fs, values, R)
    except IncompatibleUnits:
        msg = 'The units "%s" and "%s" are incompatible.' % (a.unit.string,
                                                             b.unit.string)
        raise DPSemanticError(msg)
    return ValueWithUnits(value=res, unit=R)
示例#27
0
def display_files(soup, defaults, raise_errors):
    n = 0
    for element in soup.find_all('display-file'):
        src = element.attrs.get('src', '').strip()
        element.attrs['src'] = src
        if src.startswith('github:'):
            display_file(element, defaults, raise_errors)
            n += 1
        else:
            msg = 'Unknown schema %r; I only know "github:".' % src
            if raise_errors:
                raise DPSemanticError(msg)
            else:
                note_error2(element, 'syntax error', msg)
    return n
示例#28
0
def eval_rvalue_NewFunction(rvalue, context):
    check_isinstance(rvalue, CDP.NewFunction)
    check_isinstance(rvalue.name, CDP.FName)
    fname = rvalue.name.value
    try:
        dummy_ndp = context.get_ndp_fun(fname)
    except ValueError:
        msg = 'New resource name %r not declared.' % fname
        if context.rnames:
            msg += ' Available: %s.' % ", ".join(context.rnames)
        else:
            msg += ' No resources declared so far.'
        raise DPSemanticError(msg, where=rvalue.where)

    return context.make_resource(get_name_for_fun_node(fname),
                                 dummy_ndp.get_rnames()[0])
示例#29
0
def eval_constant_collection(op, context):
    ops = get_odd_ops(unwrap_list(op.elements))
    if len(ops) == 0:
        raise DPSemanticError('empty list')
    elements = [eval_constant(_, context) for _ in ops]

    e0 = elements[0]

    u0 = e0.unit

    elements = [_.cast_value(u0) for _ in elements]

    value = FiniteCollection(set(elements), u0)
    unit = FiniteCollectionsInclusion(u0)
    vu = ValueWithUnits(value, unit)
    return vu
示例#30
0
def eval_lfunction_newresource(lf, context):
    check_isinstance(lf, CDP.NewResource)
    check_isinstance(lf.name, CDP.RName)
    rname = lf.name.value
    try:
        dummy_ndp = context.get_ndp_res(rname)
    except ValueError:
        msg = 'New resource name %r not declared.' % rname
        if context.rnames:
            msg += ' Available: %s.' % ", ".join(context.rnames)
        else:
            msg += ' No resources declared so far.'
        # msg += '\n%s' % str(e)
        raise DPSemanticError(msg, where=lf.where)

    return context.make_function(get_name_for_res_node(rname),
                                 dummy_ndp.get_fnames()[0])