def createPathAssignment(source_ref):
    if Options.getFileReferenceMode() == "original":
        path_value = ExpressionConstantRef(
            constant=[dirname(source_ref.getFilename())],
            source_ref=source_ref,
            user_provided=True)
    else:
        path_value = ExpressionMakeList(elements=(ExpressionCallNoKeywords(
            called=ExpressionAttributeLookup(source=ExpressionImportModuleHard(
                module_name="os", import_name="path", source_ref=source_ref),
                                             attribute_name="dirname",
                                             source_ref=source_ref),
            args=ExpressionMakeTuple(
                elements=(ExpressionModuleFileAttributeRef(
                    source_ref=source_ref, ), ),
                source_ref=source_ref,
            ),
            source_ref=source_ref,
        ), ),
                                        source_ref=source_ref)

    return StatementAssignmentVariable(
        variable_ref=ExpressionTargetVariableRef(variable_name="__path__",
                                                 source_ref=source_ref),
        source=path_value,
        source_ref=source_ref)
Example #2
0
 def makeImportName(import_name):
     if module_name == "__future__":
         # Make "__future__" imports tie hard immediately, they cannot be
         # any other way.
         return ExpressionImportModuleHard(module_name="__future__",
                                           import_name=import_name,
                                           source_ref=source_ref)
     else:
         # Refer to be module, or a clone of the reference if need be.
         return ExpressionImportName(module=imported_from_module,
                                     import_name=import_name,
                                     source_ref=source_ref)
 def makeImportName(import_name):
     if module_name == "__future__":
         return ExpressionImportModuleHard(module_name="__future__",
                                           import_name=import_name,
                                           source_ref=source_ref)
     else:
         return ExpressionImportName(module=ExpressionImportModule(
             module_name=module_name,
             import_list=tuple(import_names),
             level=level,
             source_ref=source_ref),
                                     import_name=import_name,
                                     source_ref=source_ref)
Example #4
0
        def makeImportName(import_name):
            if module_name == "__future__":
                return ExpressionImportModuleHard(module_name="__future__",
                                                  import_name=import_name,
                                                  source_ref=source_ref)
            else:
                # TODO: This ought to use a temporary variable for multiple
                # names, instead of importing multiple times.

                return ExpressionImportName(module=ExpressionImportModule(
                    module_name=module_name,
                    import_list=tuple(import_names),
                    level=level,
                    source_ref=source_ref),
                                            import_name=import_name,
                                            source_ref=source_ref)
def buildPrintNode(provider, node, source_ref):
    # "print" statements, should only occur with Python2.

    def wrapValue(value):
        if value.isExpressionConstantRef():
            str_value = value.getStrValue()

            if str_value is not None:
                return str_value

        return ExpressionBuiltinStr(value=value,
                                    source_ref=value.getSourceReference())

    if node.dest is not None:
        temp_scope = provider.allocateTempScope("print")

        tmp_target_variable = provider.allocateTempVariable(
            temp_scope=temp_scope, name="target")

        target_default_statement = StatementAssignmentVariable(
            variable_ref=ExpressionTargetTempVariableRef(
                variable=tmp_target_variable, source_ref=source_ref),
            source=ExpressionImportModuleHard(module_name="sys",
                                              import_name="stdout",
                                              source_ref=source_ref),
            source_ref=source_ref)

        statements = [
            StatementAssignmentVariable(
                variable_ref=ExpressionTargetTempVariableRef(
                    variable=tmp_target_variable, source_ref=source_ref),
                source=buildNode(provider=provider,
                                 node=node.dest,
                                 source_ref=source_ref),
                source_ref=source_ref),
            StatementConditional(
                condition=ExpressionComparisonIs(
                    left=ExpressionTempVariableRef(
                        variable=tmp_target_variable, source_ref=source_ref),
                    right=ExpressionConstantRef(constant=None,
                                                source_ref=source_ref),
                    source_ref=source_ref),
                yes_branch=makeStatementsSequenceFromStatement(
                    statement=target_default_statement),
                no_branch=None,
                source_ref=source_ref)
        ]

    values = buildNodeList(provider=provider,
                           nodes=node.values,
                           source_ref=source_ref)

    values = [wrapValue(value) for value in values]

    if node.dest is not None:
        print_statements = [
            StatementPrintValue(dest=ExpressionTempVariableRef(
                variable=tmp_target_variable, source_ref=source_ref),
                                value=value,
                                source_ref=source_ref) for value in values
        ]

        if node.nl:
            print_statements.append(
                StatementPrintNewline(dest=ExpressionTempVariableRef(
                    variable=tmp_target_variable, source_ref=source_ref),
                                      source_ref=source_ref))

        statements.append(
            makeTryFinallyStatement(
                tried=print_statements,
                final=StatementDelVariable(
                    variable_ref=ExpressionTargetTempVariableRef(
                        variable=tmp_target_variable, source_ref=source_ref),
                    tolerant=False,
                    source_ref=source_ref),
                source_ref=source_ref))
    else:
        statements = [
            StatementPrintValue(dest=None, value=value, source_ref=source_ref)
            for value in values
        ]

        if node.nl:
            statements.append(
                StatementPrintNewline(dest=None, source_ref=source_ref))

    return StatementsSequence(statements=statements, source_ref=source_ref)
def buildImportFromNode(provider, node, source_ref):
    # "from .. import .." statements. This may trigger a star import, or
    # multiple names being looked up from the given module variable name.
    # This is pretty complex.
    # pylint: disable=too-many-branches,too-many-locals,too-many-statements

    module_name = node.module if node.module is not None else ""
    level = node.level

    # Use default level under some circumstances.
    if level == -1:
        level = None
    elif level == 0 and not _future_specs[-1].isAbsoluteImport():
        level = None

    if level is not None:
        level_obj = makeConstantRefNode(level, source_ref, True)
    else:
        level_obj = None

    # Importing from "__future__" module may enable flags to the parser,
    # that we need to know about, handle that.
    if module_name == "__future__":
        _handleFutureImport(provider, node, source_ref)

    target_names = []
    import_names = []

    # Mapping imported "fromlist" to assigned "fromlist" if any, handling the
    # star case as well.
    for import_desc in node.names:
        object_name, local_name = import_desc.name, import_desc.asname

        if object_name == "*":
            target_names.append(None)
            assert local_name is None
        else:
            target_names.append(
                local_name if local_name is not None else object_name)

        import_names.append(object_name)

    # Star imports get special treatment.
    if None in target_names:
        # More than "*" is a syntax error in Python, need not care about this at
        # all, it's only allowed value for import list in  this case.
        assert target_names == [None]

        # Python3 made it so that these can only occur on the module level,
        # so this a syntax error if not there. For Python2 it is OK to
        # occur everywhere though.
        if not provider.isCompiledPythonModule() and python_version >= 0x300:
            raiseSyntaxError(
                "import * only allowed at module level",
                source_ref.atColumnNumber(node.col_offset),
            )

        if provider.isCompiledPythonModule():
            import_globals = ExpressionBuiltinGlobals(source_ref)
            import_locals = ExpressionBuiltinGlobals(source_ref)
        else:
            import_globals = ExpressionBuiltinGlobals(source_ref)
            import_locals = makeConstantRefNode({}, source_ref, True)

        return StatementImportStar(
            target_scope=provider.getLocalsScope(),
            module_import=ExpressionBuiltinImport(
                name=makeConstantRefNode(module_name, source_ref, True),
                globals_arg=import_globals,
                locals_arg=import_locals,
                fromlist=makeConstantRefNode(("*", ), source_ref, True),
                level=level_obj,
                source_ref=source_ref,
            ),
            source_ref=source_ref,
        )
    else:
        if module_name == "__future__":
            imported_from_module = ExpressionImportModuleHard(
                module_name="__future__", source_ref=source_ref)
        else:
            imported_from_module = ExpressionBuiltinImport(
                name=makeConstantRefNode(module_name, source_ref, True),
                globals_arg=ExpressionBuiltinGlobals(source_ref),
                locals_arg=makeConstantRefNode(None, source_ref, True),
                fromlist=makeConstantRefNode(tuple(import_names), source_ref,
                                             True),
                level=level_obj,
                source_ref=source_ref,
            )

        # If we have multiple names to import, consider each.
        multi_names = len(target_names) > 1

        statements = []

        if multi_names:
            tmp_import_from = provider.allocateTempVariable(
                temp_scope=provider.allocateTempScope("import_from"),
                name="module")

            statements.append(
                StatementAssignmentVariable(
                    variable=tmp_import_from,
                    source=imported_from_module,
                    source_ref=source_ref,
                ))

            imported_from_module = ExpressionTempVariableRef(
                variable=tmp_import_from, source_ref=source_ref)

        import_statements = []
        first = True

        for target_name, import_name in zip(target_names, import_names):
            # Make a clone of the variable reference, if we are going to use
            # another one.
            if not first:
                imported_from_module = imported_from_module.makeClone()
            first = False

            import_statements.append(
                StatementAssignmentVariableName(
                    provider=provider,
                    variable_name=mangleName(target_name, provider),
                    source=ExpressionImportName(
                        module=imported_from_module,
                        import_name=import_name,
                        level=0,
                        source_ref=source_ref,
                    ),
                    source_ref=source_ref,
                ))

        # Release the temporary module value as well.
        if multi_names:
            statements.append(
                makeTryFinallyStatement(
                    provider=provider,
                    tried=import_statements,
                    final=(StatementReleaseVariable(variable=tmp_import_from,
                                                    source_ref=source_ref), ),
                    source_ref=source_ref,
                ))
        else:
            statements.extend(import_statements)

        # Note: Each import is sequential. It can succeed, and the failure of a
        # later one is not undoing previous ones. We can therefore have a
        # sequence of imports that each only import one thing therefore.
        return StatementsSequence(statements=mergeStatements(statements),
                                  source_ref=source_ref)
def buildImportFromNode(provider, node, source_ref):
    # "from .. import .." statements. This may trigger a star import, or
    # multiple names being looked up from the given module variable name.
    # This is pretty complex.
    # pylint: disable=too-many-branches,too-many-locals,too-many-statements

    module_name = node.module if node.module is not None else ""
    level = node.level

    # Use default level under some circumstances.
    if level == -1:
        level = None
    elif level == 0 and not _future_specs[-1].isAbsoluteImport():
        level = None

    if level is not None:
        level_obj = makeConstantRefNode(level, source_ref, True)
    else:
        level_obj = None

    # Importing from "__future__" module may enable flags to the parser,
    # that we need to know about, handle that.
    if module_name == "__future__":
        _handleFutureImport(provider, node, source_ref)

    target_names = []
    import_names = []

    # Mapping imported "fromlist" to assigned "fromlist" if any, handling the
    # star case as well.
    for import_desc in node.names:
        object_name, local_name = import_desc.name, import_desc.asname

        if object_name == "*":
            target_names.append(None)
            assert local_name is None
        else:
            target_names.append(local_name if local_name is not None else object_name)

        import_names.append(object_name)

    # Star imports get special treatment.
    if None in target_names:
        # More than "*" is a syntax error in Python, need not care about this at
        # all, it's only allowed value for import list in  this case.
        assert target_names == [None]

        # Python3 made it so that these can only occur on the module level,
        # so this a syntax error if not there. For Python2 it is OK to
        # occur everywhere though.
        if not provider.isCompiledPythonModule() and python_version >= 300:
            raiseSyntaxError(
                "import * only allowed at module level",
                source_ref.atColumnNumber(node.col_offset),
            )

        if provider.isCompiledPythonModule():
            import_globals = ExpressionBuiltinGlobals(source_ref)
            import_locals = ExpressionBuiltinGlobals(source_ref)
        else:
            import_globals = ExpressionBuiltinGlobals(source_ref)
            import_locals = makeConstantRefNode({}, source_ref, True)

        return StatementImportStar(
            target_scope=provider.getModuleDictScope()
            if provider.isCompiledPythonModule()
            else provider.getFunctionLocalsScope(),
            module_import=ExpressionBuiltinImport(
                name=makeConstantRefNode(module_name, source_ref, True),
                globals_arg=import_globals,
                locals_arg=import_locals,
                fromlist=makeConstantRefNode(("*",), source_ref, True),
                level=level_obj,
                source_ref=source_ref,
            ),
            source_ref=source_ref,
        )
    else:
        if module_name == "__future__":
            imported_from_module = ExpressionImportModuleHard(
                module_name="__future__", source_ref=source_ref
            )
        else:
            imported_from_module = ExpressionBuiltinImport(
                name=makeConstantRefNode(module_name, source_ref, True),
                globals_arg=ExpressionBuiltinGlobals(source_ref),
                locals_arg=makeConstantRefNode(None, source_ref, True),
                fromlist=makeConstantRefNode(tuple(import_names), source_ref, True),
                level=level_obj,
                source_ref=source_ref,
            )

        # If we have multiple names to import, consider each.
        multi_names = len(target_names) > 1

        statements = []

        if multi_names:
            tmp_import_from = provider.allocateTempVariable(
                temp_scope=provider.allocateTempScope("import_from"), name="module"
            )

            statements.append(
                StatementAssignmentVariable(
                    variable=tmp_import_from,
                    source=imported_from_module,
                    source_ref=source_ref,
                )
            )

            imported_from_module = ExpressionTempVariableRef(
                variable=tmp_import_from, source_ref=source_ref
            )

        import_statements = []
        first = True

        for target_name, import_name in zip(target_names, import_names):
            # Make a clone of the variable reference, if we are going to use
            # another one.
            if not first:
                imported_from_module = imported_from_module.makeClone()
            first = False

            import_statements.append(
                StatementAssignmentVariableName(
                    provider=provider,
                    variable_name=mangleName(target_name, provider),
                    source=ExpressionImportName(
                        module=imported_from_module,
                        import_name=import_name,
                        level=level,
                        source_ref=source_ref,
                    ),
                    source_ref=source_ref,
                )
            )

        # Release the temporary module value as well.
        if multi_names:
            statements.append(
                makeTryFinallyStatement(
                    provider=provider,
                    tried=import_statements,
                    final=(
                        StatementReleaseVariable(
                            variable=tmp_import_from, source_ref=source_ref
                        ),
                    ),
                    source_ref=source_ref,
                )
            )
        else:
            statements.extend(import_statements)

        # Note: Each import is sequential. It can succeed, and the failure of a
        # later one is not undoing previous ones. We can therefore have a
        # sequence of imports that each only import one thing therefore.
        return StatementsSequence(
            statements=mergeStatements(statements), source_ref=source_ref
        )