internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: vyperlang/vyper

Issue:
Calldata variables cannot shadow storage variables
### What's your issue about?
In #2166 we removed the restriction re: name shadowing of memory variables and storage variables. This restriction should also be lifted for calldata variables.

### How can it be fixed?
Lift the restriction.


Discussion:
So this allows overwriting function argument values? This could make sense in practice, but would require a memcpy first before the overwrite is allowed
Not overwriting, just shadowing.

Currently this is allowed:

```python
foo: uint256

@external
def bar():
    foo: bool = True
```

but this raises with a `NamespaceCollision`:

```python
foo: uint256

@external
def bar(foo: bool):
    pass
```

Resolving patch:
diff --git a/vyper/context/types/function.py b/vyper/context/types/function.py
--- a/vyper/context/types/function.py
+++ b/vyper/context/types/function.py
@@ -280,8 +280,6 @@ def from_FunctionDef(
                 )
             if arg.arg in arguments:
                 raise ArgumentException(f"Function contains multiple inputs named {arg.arg}", arg)
-            if arg.arg in namespace["self"].members:
-                raise NamespaceCollision("Name shadows an existing storage-scoped value", arg)
             if arg.arg in namespace:
                 raise NamespaceCollision(arg.arg, arg)
 
diff --git a/vyper/parser/function_definitions/parse_external_function.py b/vyper/parser/function_definitions/parse_external_function.py
--- a/vyper/parser/function_definitions/parse_external_function.py
+++ b/vyper/parser/function_definitions/parse_external_function.py
@@ -45,14 +45,6 @@ def validate_external_function(
             "__init__ function may not have default parameters.", code
         )
 
-    # Check for duplicate variables with globals
-    for arg in sig.args:
-        if arg.name in global_ctx._globals:
-            raise FunctionDeclarationException(
-                "Variable name duplicated between " "function arguments and globals: " + arg.name,
-                code,
-            )
-
 
 def parse_external_function(
     code: ast.FunctionDef, sig: FunctionSignature, context: Context, is_contract_payable: bool


Test patch:
diff --git a/tests/parser/exceptions/test_namespace_collision.py b/tests/parser/exceptions/test_namespace_collision.py
--- a/tests/parser/exceptions/test_namespace_collision.py
+++ b/tests/parser/exceptions/test_namespace_collision.py
@@ -26,12 +26,6 @@ def foo():
     """,
     """
 x: int128
-
-@external
-def foo(x: int128): pass
-    """,
-    """
-x: int128
 x: int128
     """,
     """
@@ -60,3 +54,25 @@ def foo():
 def test_insufficient_arguments(bad_code):
     with pytest.raises(NamespaceCollision):
         compiler.compile_code(bad_code)
+
+
+pass_list = [
+    """
+x: int128
+
+@external
+def foo(x: int128): pass
+    """,
+    """
+x: int128
+
+@external
+def foo():
+    x: int128 = 1234
+    """,
+]
+
+
+@pytest.mark.parametrize("code", pass_list)
+def test_valid(code):
+    compiler.compile_code(code)
Repository: vyperlang/vyper

Issue:
Issue generating AST from bytes literal
Originally reported by @banteg at https://github.com/eth-brownie/brownie/issues/771

The following contract fails when attempting to generate certain types of outputs:

```python
# @version 0.2.4
from vyper.interfaces import ERC20

uniswap: constant(address) = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D

@external
def swap(token_in: address, token_out: address, amount_in: uint256, min_amount_out: uint256, to: address):
    ERC20(token_in).transferFrom(msg.sender, self, ERC20(token_in).balanceOf(msg.sender))
    selector: Bytes[4] = b"\x38\xed\x17\x39"
    response: Bytes[128] = raw_call(
        uniswap,
        concat(
            selector,                               # swapExactTokensForTokens
            convert(amount_in, bytes32),            # amount_in
            convert(min_amount_out, bytes32),       # min_amount_out
            convert(160, bytes32),                  # path[] payload offset
            convert(to, bytes32),                   # to
            convert(block.timestamp + 1, bytes32),  # deadline
            convert(2, bytes32),                    # path[] payload lengtgh
            convert(token_in, bytes32),             # path[0]
            convert(token_out, bytes32),            # path[1]
        ),
        max_outsize=128                             # returns uint[] amounts
    )
```

With `ast_dict` as the target output:

```python
  File "/home/computer/code/python/vyper/vyper/ast/utils.py", line 35, in parse_to_ast
    raise SyntaxException(str(e), source_code, e.lineno, e.offset) from e
vyper.exceptions.SyntaxException: bytes can only contain ASCII literal characters. (<unknown>, line 10)
  line 10:26 
        9     ERC20(token_in).transferFrom(msg.sender, self, ERC20(token_in).balanceOf(msg.sender))
  ---> 10     selector: Bytes[4] = b"8í9"
  ----------------------------------^
       11     response: Bytes[128] = raw_call(
```


Discussion:

Resolving patch:
diff --git a/vyper/ast/nodes.py b/vyper/ast/nodes.py
--- a/vyper/ast/nodes.py
+++ b/vyper/ast/nodes.py
@@ -763,11 +763,13 @@ class Bytes(Constant):
     def __init__(self, parent: Optional["VyperNode"] = None, **kwargs: dict):
         super().__init__(parent, **kwargs)
         if isinstance(self.value, str):
-            self.value = self.value.encode("utf8")
+            # convert hex string to bytes
+            length = len(self.value) // 2 - 1
+            self.value = int(self.value, 16).to_bytes(length, "big")
 
     def to_dict(self):
         ast_dict = super().to_dict()
-        ast_dict["value"] = self.value.decode("utf8")
+        ast_dict["value"] = f"0x{self.value.hex()}"
         return ast_dict
 
     @property


Test patch:
Repository: vyperlang/vyper

Issue:
line comment in last line of a function
### Version Information

* vyper Version (output of `vyper --version`):0.2.14+commit.db2606d
* OS: osx
* Python Version (output of `python --version`): 3.9.6

### What's your issue about?

if last line in a function is a comment I get this
```
x: public(uint256)

@external
def foo(ix: uint256):
    bar: uint256 = self.x
    #?? throws >> ValueError: start (7,7) precedes previous end (8,0)
```

### How can it be fixed?

no idea


Discussion:
Appears https://github.com/vyperlang/vyper/issues/1161 has come back to life
I figured out why I was not getting an error [in the previous issue](https://github.com/vyperlang/vyper/issues/1161#issuecomment-459605422). My text editor inserts a newline at the ends of files, and when the newline is there there is no issue. Here's a minimal example:
```console
(vyper) charles@cmc-thinkpad ~/vyper $ xxd repros/2410.vy 
00000000: 2320 6661 696c                           # fail
(vyper) charles@cmc-thinkpad ~/vyper $ vyper -f ir repros/2410.vy 
ValueError: start (1,6) precedes previous end (2,0)

(vyper) charles@cmc-thinkpad ~/vyper $ vim repros/2410.vy # add newline
(vyper) charles@cmc-thinkpad ~/vyper $ xxd repros/2410.vy 
00000000: 2320 7375 6363 6573 730a                 # success.
(vyper) charles@cmc-thinkpad ~/vyper $ vyper -f ir repros/2410.vy 
seq
```

However, this should have been fixed in https://github.com/vyperlang/vyper/pull/1720 ... not sure why this is cropping up again.

Resolving patch:
diff --git a/vyper/cli/vyper_compile.py b/vyper/cli/vyper_compile.py
--- a/vyper/cli/vyper_compile.py
+++ b/vyper/cli/vyper_compile.py
@@ -218,7 +218,9 @@ def compile_files(
         except ValueError:
             file_str = file_path.as_posix()
         with file_path.open() as fh:
-            contract_sources[file_str] = fh.read()
+            # trailing newline fixes python parsing bug when source ends in a comment
+            # https://bugs.python.org/issue35107
+            contract_sources[file_str] = fh.read() + "\n"
 
     show_version = False
     if "combined_json" in output_formats:
diff --git a/vyper/compiler/__init__.py b/vyper/compiler/__init__.py
--- a/vyper/compiler/__init__.py
+++ b/vyper/compiler/__init__.py
@@ -85,9 +85,7 @@ def compile_codes(
 
     out: OrderedDict = OrderedDict()
     for source_id, contract_name in enumerate(sorted(contract_sources), start=initial_id):
-        # trailing newline fixes python parsing bug when source ends in a comment
-        # https://bugs.python.org/issue35107
-        source_code = f"{contract_sources[contract_name]}\n"
+        source_code = contract_sources[contract_name]
         interfaces: Any = interface_codes
         if (
             isinstance(interfaces, dict)


Test patch:
Repository: vyperlang/vyper

Issue:
vyper.exceptions.TypeCheckFailure: pack_arguments did not return a value
### Version Information

* vyper Version (output of `vyper --version`): 0.2.16
* OS: osx
* Python Version (output of `python --version`): python3

### I tried to compile my codes using "vyper file_name.vy" and this is the error I get

Please include information like:

*Error compiling: bounty.v
![Screenshot 2021-11-03 at 9 42 39 PM](https://user-images.githubusercontent.com/54287741/140189733-b037b084-b805-4f25-aa85-eee83b0b1727.png)
y
vyper.exceptions.TypeCheckFailure: pack_arguments did not return a value

This is an unhandled internal compiler error. Please create an issue on Github to notify the developers.
* vyper
* the code that caused the failure (see [this link](https://help.github.com/articles/basic-writing-and-formatting-syntax/) for help with formatting code)
* please try running your example with the --debug flag turned on


### How can it be fixed?

Fill this in if you know how to fix it.
![Screenshot 2021-11-03 at 9 42 39 PM](https://user-images.githubusercontent.com/54287741/140189784-eb38f9fd-2994-4537-8a4a-8a6cf5f96d30.png)




Discussion:
you might be missing the return value from the interface, or the fact that you're re-using the same interface that we have defined internally might be causing problems.
Also maybe try v0.3.0?
@fubuloubu I am new to vyper and only trying to implement the withdraw and deposit functions by interfacing  the safeTransferFrom function from ERC721. Do you mind simplifying please?
@charles-cooper o.2.16 is the latest release
On v0.3.0 this throws
```
  File "/home/charles/.venvs/vyper/lib/python3.8/site-packages/vyper-0.3.0-py3.8.egg/vyper/old_codegen/external_call.py", line 124, in _external_call_helper
    assert len(contract_sig.args) == len(args_lll)
```
which is probably a dup of https://github.com/vyperlang/vyper/issues/2374
closing as this is a dup of #2374 

By the way @Eniola4031 v0.3.0 is the latest release but as of yesterday we did not have the binaries uploaded to github. This has been corrected and you can view the released binaries here https://github.com/vyperlang/vyper/releases/tag/v0.3.0

Resolving patch:
diff --git a/vyper/old_codegen/external_call.py b/vyper/old_codegen/external_call.py
--- a/vyper/old_codegen/external_call.py
+++ b/vyper/old_codegen/external_call.py
@@ -121,7 +121,7 @@ def _external_call_helper(
         gas = "gas"
 
     # sanity check
-    assert len(contract_sig.args) == len(args_lll)
+    assert len(contract_sig.base_args) <= len(args_lll) <= len(contract_sig.args)
 
     if context.is_constant() and contract_sig.mutability not in ("view", "pure"):
         # TODO is this already done in type checker?


Test patch:
Repository: vyperlang/vyper

Issue:
Cannot access `.balance` of address constants
### What's your issue about?
If I try to cal the `balance` attribute of an address constant
```python
ADDR: constant(address) = 0x000000000000000000000000000000000000dEaD

@external
def foo() -> uint256:
    return ADDR.balance
```

I get an unhandled typing exception
```python
...
~/.pyenv/versions/3.8.5/lib/python3.8/site-packages/vyper/parser/expr.py in __init__(self, node, context)
    201         self.lll_node = fn()
    202         if self.lll_node is None:
--> 203             raise TypeCheckFailure(f"{type(node).__name__} node did not produce LLL")
    204 
    205     def parse_Int(self):

TypeCheckFailure: Name node did not produce LLL

This is an unhandled internal compiler error. Please create an issue on Github to notify the developers.
https://github.com/vyperlang/vyper/issues/new?template=bug.md
```


Discussion:
I think this is related to folding of module-level constants https://github.com/vyperlang/vyper/issues/2156

Resolving patch:
diff --git a/vyper/ast/folding.py b/vyper/ast/folding.py
--- a/vyper/ast/folding.py
+++ b/vyper/ast/folding.py
@@ -220,9 +220,6 @@ def replace_constant(
     for node in vyper_module.get_descendants(vy_ast.Name, {"id": id_}, reverse=True):
         parent = node.get_ancestor()
 
-        if isinstance(parent, vy_ast.Attribute):
-            # do not replace attributes
-            continue
         if isinstance(parent, vy_ast.Call) and node == parent.func:
             # do not replace calls
             continue


Test patch:
diff --git a/tests/ast/test_folding.py b/tests/ast/test_folding.py
--- a/tests/ast/test_folding.py
+++ b/tests/ast/test_folding.py
@@ -218,6 +218,24 @@ def test_replace_userdefined_constant_no(source):
     assert vy_ast.compare_nodes(unmodified_ast, folded_ast)
 
 
+dummy_address = "0x000000000000000000000000000000000000dEaD"
+userdefined_attributes = [("b: uint256 = ADDR.balance", f"b: uint256 = {dummy_address}.balance")]
+
+
+@pytest.mark.parametrize("source", userdefined_attributes)
+def test_replace_userdefined_attribute(source):
+    preamble = f"ADDR: constant(address) = {dummy_address}"
+    l_source = f"{preamble}\n{source[0]}"
+    r_source = f"{preamble}\n{source[1]}"
+
+    l_ast = vy_ast.parse_to_ast(l_source)
+    folding.replace_user_defined_constants(l_ast)
+
+    r_ast = vy_ast.parse_to_ast(r_source)
+
+    assert vy_ast.compare_nodes(l_ast, r_ast)
+
+
 builtin_folding_functions = [("ceil(4.2)", "5"), ("floor(4.2)", "4")]
 
 builtin_folding_sources = [
Repository: vyperlang/vyper

Issue:
Constant arrays cannot be indexed with variables
### Version Information

* vyper Version: `0.2.4`
* OS: linux
* Python Version: `3.8.5`

### What's your issue about?
Attempting to use a variable to access a value within a constant array fails to compile. For example, the following code:

```python
BAR: constant(bool[3]) = [False, False, True]

@external
def foo(i: uint256):
    a: bool = BAR[i]

```

produces the following exception:

```python
  File "/home/computer/code/python/vyper/vyper/parser/expr.py", line 967, in parse_variable_location
    raise StructureException("Looking for a variable location, instead got a value", expr)
vyper.exceptions.StructureException: Looking for a variable location, instead got a value
```

### How can it be fixed?
¯\\\_(ツ)\_/¯ The issue is somewhere in `vyper.parser`, I think it will be fairly straightforward but I haven't had a chance to look yet.


Discussion:
For now the appropriate workaround is
```python
BAR: constant(bool[3]) = [False, False, True]

@external
def foo(i: uint256):
    a0: bool[3] = BAR
    a: bool = a0[i]
```

Resolving patch:
diff --git a/vyper/old_codegen/expr.py b/vyper/old_codegen/expr.py
--- a/vyper/old_codegen/expr.py
+++ b/vyper/old_codegen/expr.py
@@ -446,7 +446,15 @@ def parse_Attribute(self):
                 return get_element_ptr(sub, self.expr.attr, pos=getpos(self.expr))
 
     def parse_Subscript(self):
-        sub = Expr.parse_variable_location(self.expr.value, self.context)
+        sub = Expr(self.expr.value, self.context).lll_node
+        if sub.value == "multi":
+            # force literal to memory
+            t = LLLnode(self.context.new_internal_variable(sub.typ), typ=sub.typ, location="memory")
+            sub = LLLnode.from_list(
+                ["seq", make_setter(t, sub, pos=getpos(self.expr)), t],
+                typ=sub.typ,
+                location="memory",
+            )
 
         if isinstance(sub.typ, MappingType):
             # TODO sanity check we are in a self.my_map[i] situation
@@ -465,6 +473,7 @@ def parse_Subscript(self):
                 return
         else:
             return
+
         lll_node = get_element_ptr(sub, index, pos=getpos(self.expr))
         lll_node.mutable = sub.mutable
         return lll_node


Test patch:
diff --git a/tests/parser/types/test_lists.py b/tests/parser/types/test_lists.py
--- a/tests/parser/types/test_lists.py
+++ b/tests/parser/types/test_lists.py
@@ -395,3 +395,18 @@ def bar(_baz: Foo[3]) -> String[96]:
     c = get_contract(code)
     c_input = [[i, msg] for i, msg in enumerate(("Hello ", "world", "!!!!"))]
     assert c.bar(c_input) == "Hello world!!!!"
+
+
+def test_constant_list(get_contract, assert_tx_failed):
+    some_good_primes = [5.0, 11.0, 17.0, 29.0, 37.0, 41.0]
+    code = f"""
+MY_LIST: constant(decimal[6]) = {some_good_primes}
+@external
+def ix(i: uint256) -> decimal:
+    return MY_LIST[i]
+    """
+    c = get_contract(code)
+    for i, p in enumerate(some_good_primes):
+        assert c.ix(i) == p
+    # assert oob
+    assert_tx_failed(lambda: c.ix(len(some_good_primes) + 1))
Repository: vyperlang/vyper

Issue:
Immutable variables used in the constructor
### Version Information

* vyper Version (output of `vyper --version`): 0.3.1
* OS: macOS
* Python Version (output of `python --version`): 3.8.9

### What's your issue about?

If you use immutable variables in the constructor the variable fills with garbage(in this simplified example it remains 0).

```py
# @version 0.3.1


A: immutable(uint256)
a: public(uint256)


@external
def __init__(_a: uint256):
    A = _a
    self.a = _a  # breaks with A


@external
@view
def a1() -> uint256:
    return A
```


### How can it be fixed?

1) Immutable variables usage in constructor could be restricted by the compiler or
2) somehow set the right value.



Discussion:

Resolving patch:
diff --git a/vyper/codegen/expr.py b/vyper/codegen/expr.py
--- a/vyper/codegen/expr.py
+++ b/vyper/codegen/expr.py
@@ -326,7 +326,7 @@ def parse_Name(self):
             is_constructor = self.expr.get_ancestor(vy_ast.FunctionDef).get("name") == "__init__"
             if is_constructor:
                 # store memory position for later access in module.py in the variable record
-                memory_loc = self.context.new_variable(f"#immutable_{self.expr.id}", var.typ)
+                memory_loc = self.context.new_variable(self.expr.id, var.typ)
                 self.context.global_ctx._globals[self.expr.id].pos = memory_loc
                 # store the data offset in the variable record as well for accessing
                 data_offset = self.expr._metadata["type"].position.offset


Test patch:
diff --git a/tests/parser/features/test_immutable.py b/tests/parser/features/test_immutable.py
--- a/tests/parser/features/test_immutable.py
+++ b/tests/parser/features/test_immutable.py
@@ -32,6 +32,29 @@ def get_value() -> {typ}:
     assert c.get_value() == value
 
 
+@pytest.mark.parametrize("val", [0, 1, 2 ** 256 - 1])
+def test_usage_in_constructor(get_contract, val):
+    code = """
+A: immutable(uint256)
+a: public(uint256)
+
+
+@external
+def __init__(_a: uint256):
+    A = _a
+    self.a = A
+
+
+@external
+@view
+def a1() -> uint256:
+    return A
+    """
+
+    c = get_contract(code, val)
+    assert c.a1() == c.a() == val
+
+
 def test_multiple_immutable_values(get_contract):
     code = """
 a: immutable(uint256)
Repository: vyperlang/vyper

Issue:
[CI] memory tests failing due to london basefee calc
as of 2c73f8352635c0a433423a5b94740de1a118e508

see for instance https://github.com/vyperlang/vyper/runs/5800400118?check_suite_focus=true

![Screenshot from 2022-04-02 11-27-10](https://user-images.githubusercontent.com/3867501/161396423-bc696284-6725-4174-9ec9-aeeff03be936.png)

issue seems to be the tests now consume enough gas to trigger basefee increase. possible solutions:
- tune py-evm or base_fee_per_gas
- make the tests smaller so they consume less gas
- other?


Discussion:
this is a 0.3.2 blocker

Resolving patch:
diff --git a/vyper/codegen/core.py b/vyper/codegen/core.py
--- a/vyper/codegen/core.py
+++ b/vyper/codegen/core.py
@@ -312,28 +312,15 @@ def getpos(node):
     )
 
 
-# TODO since this is always(?) used as add_ofst(ptr, n*ptr.location.word_scale)
-# maybe the API should be `add_words_to_ofst(ptr, n)` and handle the
-# word_scale multiplication inside
+# add an offset to a pointer, keeping location and encoding info
 def add_ofst(ptr, ofst):
-    ofst = IRnode.from_list(ofst)
-    if isinstance(ptr.value, int) and isinstance(ofst.value, int):
-        # NOTE: duplicate with optimizer rule (but removing this makes a
-        # test on --no-optimize mode use too much gas)
-        ret = ptr.value + ofst.value
-    else:
-        ret = ["add", ptr, ofst]
+    ret = ["add", ptr, ofst]
     return IRnode.from_list(ret, location=ptr.location, encoding=ptr.encoding)
 
 
 # shorthand util
 def _mul(x, y):
-    x, y = IRnode.from_list(x), IRnode.from_list(y)
-    # NOTE: similar deal: duplicate with optimizer rule
-    if isinstance(x.value, int) and isinstance(y.value, int):
-        ret = x.value * y.value
-    else:
-        ret = ["mul", x, y]
+    ret = ["mul", x, y]
     return IRnode.from_list(ret)
 
 


Test patch:
diff --git a/tests/base_conftest.py b/tests/base_conftest.py
--- a/tests/base_conftest.py
+++ b/tests/base_conftest.py
@@ -85,7 +85,9 @@ def _none_addr(datatype, data):
 
 @pytest.fixture(scope="module")
 def tester():
-    custom_genesis = PyEVMBackend._generate_genesis_params(overrides={"gas_limit": 4500000})
+    # set absurdly high gas limit so that london basefee never adjusts
+    # (note: 2**63 - 1 is max that evm allows)
+    custom_genesis = PyEVMBackend._generate_genesis_params(overrides={"gas_limit": 10 ** 10})
     custom_genesis["base_fee_per_gas"] = 0
     backend = PyEVMBackend(genesis_parameters=custom_genesis)
     return EthereumTester(backend=backend)
Repository: vyperlang/vyper

Issue:
TypeError: from_annotation() takes 2 positional arguments but 6 were given
### Version Information

* vyper Version (output of `vyper --version`): 0.3.2

### What's your issue about?

I think you'll see which line causes this exception.

```
error: TypeError: from_annotation() takes 2 positional arguments but 6 were given
[25217] Failed to execute script 'vyper_compile' due to unhandled exception!
```

```
struct S:
    a: uint128
    x: uint256[3]
    b: uint240
    
b: uint8
s: S
a: uint8

@external
def __init__():
    self.b = 23
    self.a = 17
    
@external
def f():
    self.s = empty(self.s)
    self.s.x[0] = 42
    self.s.x[1] = 42
    self.s.x[2] = 42
    self.s = empty(S)
    assert self.s.x[0] == 0
    assert self.s.x[1] == 0
    assert self.s.x[2] == 0
    assert b == 23
    assert a == 17
    
@external
def g():
    self.s = empty(self.s)
    self.s.x[0] = 42
    self.s.x[1] = 42
    self.s.x[2] = 42
    self.s.a = 1
    self.s.b = 2
    self.s.x = empty(uint256[3])
    assert self.s.x[0] == 0
    assert self.s.x[1] == 0
    assert self.s.x[2] == 0
    assert b == 23
    assert a == 17
    assert self.s.a == 1
    assert self.s.b == 2
```


Discussion:
the issue is `self.s = empty(self.s)` - empty can only take type arguments. this should have a better error message though.

Resolving patch:
diff --git a/vyper/semantics/types/bases.py b/vyper/semantics/types/bases.py
--- a/vyper/semantics/types/bases.py
+++ b/vyper/semantics/types/bases.py
@@ -285,7 +285,7 @@ def canonical_abi_type(self) -> str:
         """
         return self.abi_type.selector_name()
 
-    def from_annotation(self, node: vy_ast.VyperNode, **kwargs: Any) -> None:
+    def from_annotation(self, node: vy_ast.VyperNode, *args: Any, **kwargs: Any) -> None:
         # always raises, user should have used a primitive
         raise StructureException("Value is not a type", node)
 


Test patch: