We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Code that ends in a comment (with no newline) cannot be compiled
This was previously [reported](https://github.com/ethereum/vyper/issues/1161) for Vyper, but it’s actually [a Python bug](https://bugs.python.org/issue35107):

```python
@public
def __init__():
   pass

# BUG (no newline)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `vyper/compiler.py`
Content:
```
1 from collections import (
2     OrderedDict,
3     deque,
4 )
5 from typing import (
6     Any,
7     Callable,
8     Sequence,
9     Union,
10 )
11 import warnings
12 
13 import asttokens
14 
15 from vyper import (
16     compile_lll,
17     optimizer,
18 )
19 from vyper.ast_utils import (
20     ast_to_dict,
21 )
22 from vyper.opcodes import (
23     opcodes,
24 )
25 from vyper.parser import (
26     parser,
27 )
28 from vyper.signatures import (
29     sig_utils,
30 )
31 from vyper.signatures.interface import (
32     extract_external_interface,
33     extract_interface_str,
34 )
35 from vyper.typing import (
36     ContractCodes,
37     InterfaceDict,
38     InterfaceImports,
39     OutputDict,
40     OutputFormats,
41 )
42 
43 
44 def __compile(code, interface_codes=None, *args, **kwargs):
45     ast = parser.parse_to_ast(code)
46     lll = parser.parse_tree_to_lll(
47         ast,
48         code,
49         interface_codes=interface_codes,
50         runtime_only=kwargs.get('bytecode_runtime', False)
51     )
52     opt_lll = optimizer.optimize(lll)
53     asm = compile_lll.compile_to_assembly(opt_lll)
54 
55     def find_nested_opcode(asm_list, key):
56         if key in asm_list:
57             return True
58         else:
59             sublists = [sub for sub in asm_list if isinstance(sub, list)]
60             return any(find_nested_opcode(x, key) for x in sublists)
61 
62     if find_nested_opcode(asm, 'DEBUG'):
63         warnings.warn(
64             'This code contains DEBUG opcodes! The DEBUG opcode will only work in '
65             'a supported EVM! It will FAIL on all other nodes!'
66         )
67 
68     c, line_number_map = compile_lll.assembly_to_evm(asm)
69     return c
70 
71 
72 def gas_estimate(origcode, *args, **kwargs):
73     o = {}
74     code = optimizer.optimize(parser.parse_to_lll(origcode, *args, **kwargs))
75 
76     # Extract the stuff inside the LLL bracket
77     if code.value == 'seq':
78         if len(code.args) > 0 and code.args[-1].value == 'return':
79             code = code.args[-1].args[1].args[0]
80 
81     assert code.value == 'seq'
82     for arg in code.args:
83         if arg.func_name is not None:
84             o[arg.func_name] = arg.total_gas
85     return o
86 
87 
88 def mk_full_signature(code, *args, **kwargs):
89     abi = sig_utils.mk_full_signature(parser.parse_to_ast(code), *args, **kwargs)
90     # Add gas estimates for each function to ABI
91     gas_estimates = gas_estimate(code, *args, **kwargs)
92     for func in abi:
93         try:
94             func_signature = func['name']
95         except KeyError:
96             # constructor and fallback functions don't have a name
97             continue
98 
99         func_name, _, _ = func_signature.partition('(')
100         # This check ensures we skip __init__ since it has no estimate
101         if func_name in gas_estimates:
102             # TODO: mutation
103             func['gas'] = gas_estimates[func_name]
104     return abi
105 
106 
107 def get_asm(asm_list):
108     output_string = ''
109     skip_newlines = 0
110     for node in asm_list:
111         if isinstance(node, list):
112             output_string += get_asm(node)
113             continue
114 
115         is_push = isinstance(node, str) and node.startswith('PUSH')
116 
117         output_string += str(node) + ' '
118         if skip_newlines:
119             skip_newlines -= 1
120         elif is_push:
121             skip_newlines = int(node[4:]) - 1
122         else:
123             output_string += '\n'
124     return output_string
125 
126 
127 def get_source_map(code, contract_name, interface_codes=None, runtime_only=True, source_id=0):
128     asm_list = compile_lll.compile_to_assembly(
129         optimizer.optimize(
130             parser.parse_to_lll(
131                 code,
132                 runtime_only=runtime_only,
133                 interface_codes=interface_codes)))
134     c, line_number_map = compile_lll.assembly_to_evm(asm_list)
135     # Sort line_number_map
136     out = OrderedDict()
137     for k in sorted(line_number_map.keys()):
138         out[k] = line_number_map[k]
139 
140     out['pc_pos_map_compressed'] = compress_source_map(
141         code,
142         out['pc_pos_map'],
143         out['pc_jump_map'],
144         source_id
145     )
146     out['pc_pos_map'] = dict((k, v) for k, v in out['pc_pos_map'].items() if v)
147     return out
148 
149 
150 def compress_source_map(code, pos_map, jump_map, source_id):
151     linenos = asttokens.LineNumbers(code)
152     compressed_map = f"-1:-1:{source_id}:-;"
153     last_pos = [-1, -1, source_id]
154 
155     for pc in sorted(pos_map)[1:]:
156         current_pos = [-1, -1, source_id]
157         if pos_map[pc]:
158             current_pos[0] = linenos.line_to_offset(*pos_map[pc][:2])
159             current_pos[1] = linenos.line_to_offset(*pos_map[pc][2:])-current_pos[0]
160 
161         if pc in jump_map:
162             current_pos.append(jump_map[pc])
163 
164         for i in range(2, -1, -1):
165             if current_pos[i] != last_pos[i]:
166                 last_pos[i] = current_pos[i]
167             elif len(current_pos) == i+1:
168                 current_pos.pop()
169             else:
170                 current_pos[i] = ""
171 
172         compressed_map += ":".join(str(i) for i in current_pos) + ";"
173 
174     return compressed_map
175 
176 
177 def expand_source_map(compressed_map):
178     source_map = [_expand_row(i) if i else None for i in compressed_map.split(';')[:-1]]
179 
180     for i, value in enumerate(source_map[1:], 1):
181         if value is None:
182             source_map[i] = source_map[i - 1][:3] + [None]
183             continue
184         for x in range(3):
185             if source_map[i][x] is None:
186                 source_map[i][x] = source_map[i - 1][x]
187 
188     return source_map
189 
190 
191 def _expand_row(row):
192     result = [None] * 4
193     for i, value in enumerate(row.split(':')):
194         if value:
195             result[i] = value if i == 3 else int(value)
196     return result
197 
198 
199 def get_opcodes(code, contract_name, bytecodes_runtime=False, interface_codes=None):
200     bytecode = __compile(
201         code,
202         bytecode_runtime=bytecodes_runtime,
203         interface_codes=interface_codes
204     ).hex().upper()
205     bytecode = deque(bytecode[i:i + 2] for i in range(0, len(bytecode), 2))
206     opcode_map = dict((v[0], k) for k, v in opcodes.items())
207     opcode_str = ""
208 
209     while bytecode:
210         op = int(bytecode.popleft(), 16)
211         opcode_str += opcode_map[op] + " "
212         if "PUSH" not in opcode_map[op]:
213             continue
214         push_len = int(opcode_map[op][4:])
215         opcode_str += "0x" + "".join(bytecode.popleft() for i in range(push_len)) + " "
216 
217     return opcode_str[:-1]
218 
219 
220 def _mk_abi_output(code, contract_name, interface_codes, source_id):
221     return mk_full_signature(code, interface_codes=interface_codes)
222 
223 
224 def _mk_bytecode_output(code, contract_name, interface_codes, source_id):
225     return '0x' + __compile(code, interface_codes=interface_codes).hex()
226 
227 
228 def _mk_bytecode_runtime_output(code, contract_name, interface_codes, source_id):
229     return '0x' + __compile(code, bytecode_runtime=True, interface_codes=interface_codes).hex()
230 
231 
232 def _mk_ir_output(code, contract_name, interface_codes, source_id):
233     return optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))
234 
235 
236 def _mk_asm_output(code, contract_name, interface_codes, source_id):
237     return get_asm(compile_lll.compile_to_assembly(
238         optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))
239     ))
240 
241 
242 def _mk_source_map_output(code, contract_name, interface_codes, source_id):
243     return get_source_map(
244         code,
245         contract_name,
246         interface_codes=interface_codes,
247         runtime_only=True,
248         source_id=source_id
249     )
250 
251 
252 def _mk_method_identifiers_output(code, contract_name, interface_codes, source_id):
253     return sig_utils.mk_method_identifiers(code, interface_codes=interface_codes)
254 
255 
256 def _mk_interface_output(code, contract_name, interface_codes, source_id):
257     return extract_interface_str(code, contract_name, interface_codes=interface_codes)
258 
259 
260 def _mk_external_interface_output(code, contract_name, interface_codes, source_id):
261     return extract_external_interface(code, contract_name, interface_codes=interface_codes)
262 
263 
264 def _mk_opcodes(code, contract_name, interface_codes, source_id):
265     return get_opcodes(code, contract_name, interface_codes=interface_codes)
266 
267 
268 def _mk_opcodes_runtime(code, contract_name, interface_codes, source_id):
269     return get_opcodes(code, contract_name, bytecodes_runtime=True, interface_codes=interface_codes)
270 
271 
272 def _mk_ast_dict(code, contract_name, interface_codes, source_id):
273     o = {
274         'contract_name': contract_name,
275         'ast': ast_to_dict(parser.parse_to_ast(code, source_id))
276     }
277     return o
278 
279 
280 output_formats_map = {
281     'abi': _mk_abi_output,
282     'ast_dict': _mk_ast_dict,
283     'bytecode': _mk_bytecode_output,
284     'bytecode_runtime': _mk_bytecode_runtime_output,
285     'ir': _mk_ir_output,
286     'asm': _mk_asm_output,
287     'source_map': _mk_source_map_output,
288     'method_identifiers': _mk_method_identifiers_output,
289     'interface': _mk_interface_output,
290     'external_interface': _mk_external_interface_output,
291     'opcodes': _mk_opcodes,
292     'opcodes_runtime': _mk_opcodes_runtime,
293 }
294 
295 
296 def compile_codes(contract_sources: ContractCodes,
297                   output_formats: Union[OutputDict, OutputFormats, None] = None,
298                   exc_handler: Union[Callable, None] = None,
299                   interface_codes: Union[InterfaceDict, InterfaceImports, None] = None,
300                   initial_id: int = 0) -> OrderedDict:
301 
302     if output_formats is None:
303         output_formats = ('bytecode',)
304     if isinstance(output_formats, Sequence):
305         output_formats = dict((k, output_formats) for k in contract_sources.keys())
306 
307     out: OrderedDict = OrderedDict()
308     for source_id, contract_name in enumerate(sorted(contract_sources), start=initial_id):
309         code = contract_sources[contract_name]
310         for output_format in output_formats[contract_name]:
311             if output_format not in output_formats_map:
312                 raise ValueError(f'Unsupported format type {repr(output_format)}')
313 
314             try:
315                 interfaces: Any = interface_codes
316                 if (
317                     isinstance(interfaces, dict) and
318                     contract_name in interfaces and
319                     isinstance(interfaces[contract_name], dict)
320                 ):
321                     interfaces = interfaces[contract_name]
322                 out.setdefault(contract_name, {})
323                 out[contract_name][output_format] = output_formats_map[output_format](
324                     code=code,
325                     contract_name=contract_name,
326                     interface_codes=interfaces,
327                     source_id=source_id
328                 )
329             except Exception as exc:
330                 if exc_handler is not None:
331                     exc_handler(contract_name, exc)
332                 else:
333                     raise exc
334 
335     return out
336 
337 
338 UNKNOWN_CONTRACT_NAME = '<unknown>'
339 
340 
341 def compile_code(code, output_formats=None, interface_codes=None):
342     contract_sources = {UNKNOWN_CONTRACT_NAME: code}
343 
344     return compile_codes(
345         contract_sources,
346         output_formats,
347         interface_codes=interface_codes,
348     )[UNKNOWN_CONTRACT_NAME]
349
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/vyper/compiler.py b/vyper/compiler.py
--- a/vyper/compiler.py
+++ b/vyper/compiler.py
@@ -321,7 +321,9 @@
                     interfaces = interfaces[contract_name]
                 out.setdefault(contract_name, {})
                 out[contract_name][output_format] = output_formats_map[output_format](
-                    code=code,
+                    # trailing newline fixes python parsing bug when source ends in a comment
+                    # https://bugs.python.org/issue35107
+                    code=f"{code}\n",
                     contract_name=contract_name,
                     interface_codes=interfaces,
                     source_id=source_id

{"golden_diff": "diff --git a/vyper/compiler.py b/vyper/compiler.py\n--- a/vyper/compiler.py\n+++ b/vyper/compiler.py\n@@ -321,7 +321,9 @@\n                     interfaces = interfaces[contract_name]\n                 out.setdefault(contract_name, {})\n                 out[contract_name][output_format] = output_formats_map[output_format](\n-                    code=code,\n+                    # trailing newline fixes python parsing bug when source ends in a comment\n+                    # https://bugs.python.org/issue35107\n+                    code=f\"{code}\\n\",\n                     contract_name=contract_name,\n                     interface_codes=interfaces,\n                     source_id=source_id\n", "issue": "Code that ends in a comment (with no newline) cannot be compiled\nThis was previously [reported](https://github.com/ethereum/vyper/issues/1161) for Vyper, but it\u2019s actually [a Python bug](https://bugs.python.org/issue35107):\r\n\r\n```python\r\n@public\r\ndef __init__():\r\n   pass\r\n\r\n# BUG (no newline)\r\n```\n", "before_files": [{"content": "from collections import (\n    OrderedDict,\n    deque,\n)\nfrom typing import (\n    Any,\n    Callable,\n    Sequence,\n    Union,\n)\nimport warnings\n\nimport asttokens\n\nfrom vyper import (\n    compile_lll,\n    optimizer,\n)\nfrom vyper.ast_utils import (\n    ast_to_dict,\n)\nfrom vyper.opcodes import (\n    opcodes,\n)\nfrom vyper.parser import (\n    parser,\n)\nfrom vyper.signatures import (\n    sig_utils,\n)\nfrom vyper.signatures.interface import (\n    extract_external_interface,\n    extract_interface_str,\n)\nfrom vyper.typing import (\n    ContractCodes,\n    InterfaceDict,\n    InterfaceImports,\n    OutputDict,\n    OutputFormats,\n)\n\n\ndef __compile(code, interface_codes=None, *args, **kwargs):\n    ast = parser.parse_to_ast(code)\n    lll = parser.parse_tree_to_lll(\n        ast,\n        code,\n        interface_codes=interface_codes,\n        runtime_only=kwargs.get('bytecode_runtime', False)\n    )\n    opt_lll = optimizer.optimize(lll)\n    asm = compile_lll.compile_to_assembly(opt_lll)\n\n    def find_nested_opcode(asm_list, key):\n        if key in asm_list:\n            return True\n        else:\n            sublists = [sub for sub in asm_list if isinstance(sub, list)]\n            return any(find_nested_opcode(x, key) for x in sublists)\n\n    if find_nested_opcode(asm, 'DEBUG'):\n        warnings.warn(\n            'This code contains DEBUG opcodes! The DEBUG opcode will only work in '\n            'a supported EVM! It will FAIL on all other nodes!'\n        )\n\n    c, line_number_map = compile_lll.assembly_to_evm(asm)\n    return c\n\n\ndef gas_estimate(origcode, *args, **kwargs):\n    o = {}\n    code = optimizer.optimize(parser.parse_to_lll(origcode, *args, **kwargs))\n\n    # Extract the stuff inside the LLL bracket\n    if code.value == 'seq':\n        if len(code.args) > 0 and code.args[-1].value == 'return':\n            code = code.args[-1].args[1].args[0]\n\n    assert code.value == 'seq'\n    for arg in code.args:\n        if arg.func_name is not None:\n            o[arg.func_name] = arg.total_gas\n    return o\n\n\ndef mk_full_signature(code, *args, **kwargs):\n    abi = sig_utils.mk_full_signature(parser.parse_to_ast(code), *args, **kwargs)\n    # Add gas estimates for each function to ABI\n    gas_estimates = gas_estimate(code, *args, **kwargs)\n    for func in abi:\n        try:\n            func_signature = func['name']\n        except KeyError:\n            # constructor and fallback functions don't have a name\n            continue\n\n        func_name, _, _ = func_signature.partition('(')\n        # This check ensures we skip __init__ since it has no estimate\n        if func_name in gas_estimates:\n            # TODO: mutation\n            func['gas'] = gas_estimates[func_name]\n    return abi\n\n\ndef get_asm(asm_list):\n    output_string = ''\n    skip_newlines = 0\n    for node in asm_list:\n        if isinstance(node, list):\n            output_string += get_asm(node)\n            continue\n\n        is_push = isinstance(node, str) and node.startswith('PUSH')\n\n        output_string += str(node) + ' '\n        if skip_newlines:\n            skip_newlines -= 1\n        elif is_push:\n            skip_newlines = int(node[4:]) - 1\n        else:\n            output_string += '\\n'\n    return output_string\n\n\ndef get_source_map(code, contract_name, interface_codes=None, runtime_only=True, source_id=0):\n    asm_list = compile_lll.compile_to_assembly(\n        optimizer.optimize(\n            parser.parse_to_lll(\n                code,\n                runtime_only=runtime_only,\n                interface_codes=interface_codes)))\n    c, line_number_map = compile_lll.assembly_to_evm(asm_list)\n    # Sort line_number_map\n    out = OrderedDict()\n    for k in sorted(line_number_map.keys()):\n        out[k] = line_number_map[k]\n\n    out['pc_pos_map_compressed'] = compress_source_map(\n        code,\n        out['pc_pos_map'],\n        out['pc_jump_map'],\n        source_id\n    )\n    out['pc_pos_map'] = dict((k, v) for k, v in out['pc_pos_map'].items() if v)\n    return out\n\n\ndef compress_source_map(code, pos_map, jump_map, source_id):\n    linenos = asttokens.LineNumbers(code)\n    compressed_map = f\"-1:-1:{source_id}:-;\"\n    last_pos = [-1, -1, source_id]\n\n    for pc in sorted(pos_map)[1:]:\n        current_pos = [-1, -1, source_id]\n        if pos_map[pc]:\n            current_pos[0] = linenos.line_to_offset(*pos_map[pc][:2])\n            current_pos[1] = linenos.line_to_offset(*pos_map[pc][2:])-current_pos[0]\n\n        if pc in jump_map:\n            current_pos.append(jump_map[pc])\n\n        for i in range(2, -1, -1):\n            if current_pos[i] != last_pos[i]:\n                last_pos[i] = current_pos[i]\n            elif len(current_pos) == i+1:\n                current_pos.pop()\n            else:\n                current_pos[i] = \"\"\n\n        compressed_map += \":\".join(str(i) for i in current_pos) + \";\"\n\n    return compressed_map\n\n\ndef expand_source_map(compressed_map):\n    source_map = [_expand_row(i) if i else None for i in compressed_map.split(';')[:-1]]\n\n    for i, value in enumerate(source_map[1:], 1):\n        if value is None:\n            source_map[i] = source_map[i - 1][:3] + [None]\n            continue\n        for x in range(3):\n            if source_map[i][x] is None:\n                source_map[i][x] = source_map[i - 1][x]\n\n    return source_map\n\n\ndef _expand_row(row):\n    result = [None] * 4\n    for i, value in enumerate(row.split(':')):\n        if value:\n            result[i] = value if i == 3 else int(value)\n    return result\n\n\ndef get_opcodes(code, contract_name, bytecodes_runtime=False, interface_codes=None):\n    bytecode = __compile(\n        code,\n        bytecode_runtime=bytecodes_runtime,\n        interface_codes=interface_codes\n    ).hex().upper()\n    bytecode = deque(bytecode[i:i + 2] for i in range(0, len(bytecode), 2))\n    opcode_map = dict((v[0], k) for k, v in opcodes.items())\n    opcode_str = \"\"\n\n    while bytecode:\n        op = int(bytecode.popleft(), 16)\n        opcode_str += opcode_map[op] + \" \"\n        if \"PUSH\" not in opcode_map[op]:\n            continue\n        push_len = int(opcode_map[op][4:])\n        opcode_str += \"0x\" + \"\".join(bytecode.popleft() for i in range(push_len)) + \" \"\n\n    return opcode_str[:-1]\n\n\ndef _mk_abi_output(code, contract_name, interface_codes, source_id):\n    return mk_full_signature(code, interface_codes=interface_codes)\n\n\ndef _mk_bytecode_output(code, contract_name, interface_codes, source_id):\n    return '0x' + __compile(code, interface_codes=interface_codes).hex()\n\n\ndef _mk_bytecode_runtime_output(code, contract_name, interface_codes, source_id):\n    return '0x' + __compile(code, bytecode_runtime=True, interface_codes=interface_codes).hex()\n\n\ndef _mk_ir_output(code, contract_name, interface_codes, source_id):\n    return optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))\n\n\ndef _mk_asm_output(code, contract_name, interface_codes, source_id):\n    return get_asm(compile_lll.compile_to_assembly(\n        optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))\n    ))\n\n\ndef _mk_source_map_output(code, contract_name, interface_codes, source_id):\n    return get_source_map(\n        code,\n        contract_name,\n        interface_codes=interface_codes,\n        runtime_only=True,\n        source_id=source_id\n    )\n\n\ndef _mk_method_identifiers_output(code, contract_name, interface_codes, source_id):\n    return sig_utils.mk_method_identifiers(code, interface_codes=interface_codes)\n\n\ndef _mk_interface_output(code, contract_name, interface_codes, source_id):\n    return extract_interface_str(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_external_interface_output(code, contract_name, interface_codes, source_id):\n    return extract_external_interface(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_opcodes(code, contract_name, interface_codes, source_id):\n    return get_opcodes(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_opcodes_runtime(code, contract_name, interface_codes, source_id):\n    return get_opcodes(code, contract_name, bytecodes_runtime=True, interface_codes=interface_codes)\n\n\ndef _mk_ast_dict(code, contract_name, interface_codes, source_id):\n    o = {\n        'contract_name': contract_name,\n        'ast': ast_to_dict(parser.parse_to_ast(code, source_id))\n    }\n    return o\n\n\noutput_formats_map = {\n    'abi': _mk_abi_output,\n    'ast_dict': _mk_ast_dict,\n    'bytecode': _mk_bytecode_output,\n    'bytecode_runtime': _mk_bytecode_runtime_output,\n    'ir': _mk_ir_output,\n    'asm': _mk_asm_output,\n    'source_map': _mk_source_map_output,\n    'method_identifiers': _mk_method_identifiers_output,\n    'interface': _mk_interface_output,\n    'external_interface': _mk_external_interface_output,\n    'opcodes': _mk_opcodes,\n    'opcodes_runtime': _mk_opcodes_runtime,\n}\n\n\ndef compile_codes(contract_sources: ContractCodes,\n                  output_formats: Union[OutputDict, OutputFormats, None] = None,\n                  exc_handler: Union[Callable, None] = None,\n                  interface_codes: Union[InterfaceDict, InterfaceImports, None] = None,\n                  initial_id: int = 0) -> OrderedDict:\n\n    if output_formats is None:\n        output_formats = ('bytecode',)\n    if isinstance(output_formats, Sequence):\n        output_formats = dict((k, output_formats) for k in contract_sources.keys())\n\n    out: OrderedDict = OrderedDict()\n    for source_id, contract_name in enumerate(sorted(contract_sources), start=initial_id):\n        code = contract_sources[contract_name]\n        for output_format in output_formats[contract_name]:\n            if output_format not in output_formats_map:\n                raise ValueError(f'Unsupported format type {repr(output_format)}')\n\n            try:\n                interfaces: Any = interface_codes\n                if (\n                    isinstance(interfaces, dict) and\n                    contract_name in interfaces and\n                    isinstance(interfaces[contract_name], dict)\n                ):\n                    interfaces = interfaces[contract_name]\n                out.setdefault(contract_name, {})\n                out[contract_name][output_format] = output_formats_map[output_format](\n                    code=code,\n                    contract_name=contract_name,\n                    interface_codes=interfaces,\n                    source_id=source_id\n                )\n            except Exception as exc:\n                if exc_handler is not None:\n                    exc_handler(contract_name, exc)\n                else:\n                    raise exc\n\n    return out\n\n\nUNKNOWN_CONTRACT_NAME = '<unknown>'\n\n\ndef compile_code(code, output_formats=None, interface_codes=None):\n    contract_sources = {UNKNOWN_CONTRACT_NAME: code}\n\n    return compile_codes(\n        contract_sources,\n        output_formats,\n        interface_codes=interface_codes,\n    )[UNKNOWN_CONTRACT_NAME]\n", "path": "vyper/compiler.py"}], "after_files": [{"content": "from collections import (\n    OrderedDict,\n    deque,\n)\nfrom typing import (\n    Any,\n    Callable,\n    Sequence,\n    Union,\n)\nimport warnings\n\nimport asttokens\n\nfrom vyper import (\n    compile_lll,\n    optimizer,\n)\nfrom vyper.ast_utils import (\n    ast_to_dict,\n)\nfrom vyper.opcodes import (\n    opcodes,\n)\nfrom vyper.parser import (\n    parser,\n)\nfrom vyper.signatures import (\n    sig_utils,\n)\nfrom vyper.signatures.interface import (\n    extract_external_interface,\n    extract_interface_str,\n)\nfrom vyper.typing import (\n    ContractCodes,\n    InterfaceDict,\n    InterfaceImports,\n    OutputDict,\n    OutputFormats,\n)\n\n\ndef __compile(code, interface_codes=None, *args, **kwargs):\n    ast = parser.parse_to_ast(code)\n    lll = parser.parse_tree_to_lll(\n        ast,\n        code,\n        interface_codes=interface_codes,\n        runtime_only=kwargs.get('bytecode_runtime', False)\n    )\n    opt_lll = optimizer.optimize(lll)\n    asm = compile_lll.compile_to_assembly(opt_lll)\n\n    def find_nested_opcode(asm_list, key):\n        if key in asm_list:\n            return True\n        else:\n            sublists = [sub for sub in asm_list if isinstance(sub, list)]\n            return any(find_nested_opcode(x, key) for x in sublists)\n\n    if find_nested_opcode(asm, 'DEBUG'):\n        warnings.warn(\n            'This code contains DEBUG opcodes! The DEBUG opcode will only work in '\n            'a supported EVM! It will FAIL on all other nodes!'\n        )\n\n    c, line_number_map = compile_lll.assembly_to_evm(asm)\n    return c\n\n\ndef gas_estimate(origcode, *args, **kwargs):\n    o = {}\n    code = optimizer.optimize(parser.parse_to_lll(origcode, *args, **kwargs))\n\n    # Extract the stuff inside the LLL bracket\n    if code.value == 'seq':\n        if len(code.args) > 0 and code.args[-1].value == 'return':\n            code = code.args[-1].args[1].args[0]\n\n    assert code.value == 'seq'\n    for arg in code.args:\n        if arg.func_name is not None:\n            o[arg.func_name] = arg.total_gas\n    return o\n\n\ndef mk_full_signature(code, *args, **kwargs):\n    abi = sig_utils.mk_full_signature(parser.parse_to_ast(code), *args, **kwargs)\n    # Add gas estimates for each function to ABI\n    gas_estimates = gas_estimate(code, *args, **kwargs)\n    for func in abi:\n        try:\n            func_signature = func['name']\n        except KeyError:\n            # constructor and fallback functions don't have a name\n            continue\n\n        func_name, _, _ = func_signature.partition('(')\n        # This check ensures we skip __init__ since it has no estimate\n        if func_name in gas_estimates:\n            # TODO: mutation\n            func['gas'] = gas_estimates[func_name]\n    return abi\n\n\ndef get_asm(asm_list):\n    output_string = ''\n    skip_newlines = 0\n    for node in asm_list:\n        if isinstance(node, list):\n            output_string += get_asm(node)\n            continue\n\n        is_push = isinstance(node, str) and node.startswith('PUSH')\n\n        output_string += str(node) + ' '\n        if skip_newlines:\n            skip_newlines -= 1\n        elif is_push:\n            skip_newlines = int(node[4:]) - 1\n        else:\n            output_string += '\\n'\n    return output_string\n\n\ndef get_source_map(code, contract_name, interface_codes=None, runtime_only=True, source_id=0):\n    asm_list = compile_lll.compile_to_assembly(\n        optimizer.optimize(\n            parser.parse_to_lll(\n                code,\n                runtime_only=runtime_only,\n                interface_codes=interface_codes)))\n    c, line_number_map = compile_lll.assembly_to_evm(asm_list)\n    # Sort line_number_map\n    out = OrderedDict()\n    for k in sorted(line_number_map.keys()):\n        out[k] = line_number_map[k]\n\n    out['pc_pos_map_compressed'] = compress_source_map(\n        code,\n        out['pc_pos_map'],\n        out['pc_jump_map'],\n        source_id\n    )\n    out['pc_pos_map'] = dict((k, v) for k, v in out['pc_pos_map'].items() if v)\n    return out\n\n\ndef compress_source_map(code, pos_map, jump_map, source_id):\n    linenos = asttokens.LineNumbers(code)\n    compressed_map = f\"-1:-1:{source_id}:-;\"\n    last_pos = [-1, -1, source_id]\n\n    for pc in sorted(pos_map)[1:]:\n        current_pos = [-1, -1, source_id]\n        if pos_map[pc]:\n            current_pos[0] = linenos.line_to_offset(*pos_map[pc][:2])\n            current_pos[1] = linenos.line_to_offset(*pos_map[pc][2:])-current_pos[0]\n\n        if pc in jump_map:\n            current_pos.append(jump_map[pc])\n\n        for i in range(2, -1, -1):\n            if current_pos[i] != last_pos[i]:\n                last_pos[i] = current_pos[i]\n            elif len(current_pos) == i+1:\n                current_pos.pop()\n            else:\n                current_pos[i] = \"\"\n\n        compressed_map += \":\".join(str(i) for i in current_pos) + \";\"\n\n    return compressed_map\n\n\ndef expand_source_map(compressed_map):\n    source_map = [_expand_row(i) if i else None for i in compressed_map.split(';')[:-1]]\n\n    for i, value in enumerate(source_map[1:], 1):\n        if value is None:\n            source_map[i] = source_map[i - 1][:3] + [None]\n            continue\n        for x in range(3):\n            if source_map[i][x] is None:\n                source_map[i][x] = source_map[i - 1][x]\n\n    return source_map\n\n\ndef _expand_row(row):\n    result = [None] * 4\n    for i, value in enumerate(row.split(':')):\n        if value:\n            result[i] = value if i == 3 else int(value)\n    return result\n\n\ndef get_opcodes(code, contract_name, bytecodes_runtime=False, interface_codes=None):\n    bytecode = __compile(\n        code,\n        bytecode_runtime=bytecodes_runtime,\n        interface_codes=interface_codes\n    ).hex().upper()\n    bytecode = deque(bytecode[i:i + 2] for i in range(0, len(bytecode), 2))\n    opcode_map = dict((v[0], k) for k, v in opcodes.items())\n    opcode_str = \"\"\n\n    while bytecode:\n        op = int(bytecode.popleft(), 16)\n        opcode_str += opcode_map[op] + \" \"\n        if \"PUSH\" not in opcode_map[op]:\n            continue\n        push_len = int(opcode_map[op][4:])\n        opcode_str += \"0x\" + \"\".join(bytecode.popleft() for i in range(push_len)) + \" \"\n\n    return opcode_str[:-1]\n\n\ndef _mk_abi_output(code, contract_name, interface_codes, source_id):\n    return mk_full_signature(code, interface_codes=interface_codes)\n\n\ndef _mk_bytecode_output(code, contract_name, interface_codes, source_id):\n    return '0x' + __compile(code, interface_codes=interface_codes).hex()\n\n\ndef _mk_bytecode_runtime_output(code, contract_name, interface_codes, source_id):\n    return '0x' + __compile(code, bytecode_runtime=True, interface_codes=interface_codes).hex()\n\n\ndef _mk_ir_output(code, contract_name, interface_codes, source_id):\n    return optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))\n\n\ndef _mk_asm_output(code, contract_name, interface_codes, source_id):\n    return get_asm(compile_lll.compile_to_assembly(\n        optimizer.optimize(parser.parse_to_lll(code, interface_codes=interface_codes))\n    ))\n\n\ndef _mk_source_map_output(code, contract_name, interface_codes, source_id):\n    return get_source_map(\n        code,\n        contract_name,\n        interface_codes=interface_codes,\n        runtime_only=True,\n        source_id=source_id\n    )\n\n\ndef _mk_method_identifiers_output(code, contract_name, interface_codes, source_id):\n    return sig_utils.mk_method_identifiers(code, interface_codes=interface_codes)\n\n\ndef _mk_interface_output(code, contract_name, interface_codes, source_id):\n    return extract_interface_str(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_external_interface_output(code, contract_name, interface_codes, source_id):\n    return extract_external_interface(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_opcodes(code, contract_name, interface_codes, source_id):\n    return get_opcodes(code, contract_name, interface_codes=interface_codes)\n\n\ndef _mk_opcodes_runtime(code, contract_name, interface_codes, source_id):\n    return get_opcodes(code, contract_name, bytecodes_runtime=True, interface_codes=interface_codes)\n\n\ndef _mk_ast_dict(code, contract_name, interface_codes, source_id):\n    o = {\n        'contract_name': contract_name,\n        'ast': ast_to_dict(parser.parse_to_ast(code, source_id))\n    }\n    return o\n\n\noutput_formats_map = {\n    'abi': _mk_abi_output,\n    'ast_dict': _mk_ast_dict,\n    'bytecode': _mk_bytecode_output,\n    'bytecode_runtime': _mk_bytecode_runtime_output,\n    'ir': _mk_ir_output,\n    'asm': _mk_asm_output,\n    'source_map': _mk_source_map_output,\n    'method_identifiers': _mk_method_identifiers_output,\n    'interface': _mk_interface_output,\n    'external_interface': _mk_external_interface_output,\n    'opcodes': _mk_opcodes,\n    'opcodes_runtime': _mk_opcodes_runtime,\n}\n\n\ndef compile_codes(contract_sources: ContractCodes,\n                  output_formats: Union[OutputDict, OutputFormats, None] = None,\n                  exc_handler: Union[Callable, None] = None,\n                  interface_codes: Union[InterfaceDict, InterfaceImports, None] = None,\n                  initial_id: int = 0) -> OrderedDict:\n\n    if output_formats is None:\n        output_formats = ('bytecode',)\n    if isinstance(output_formats, Sequence):\n        output_formats = dict((k, output_formats) for k in contract_sources.keys())\n\n    out: OrderedDict = OrderedDict()\n    for source_id, contract_name in enumerate(sorted(contract_sources), start=initial_id):\n        code = contract_sources[contract_name]\n        for output_format in output_formats[contract_name]:\n            if output_format not in output_formats_map:\n                raise ValueError(f'Unsupported format type {repr(output_format)}')\n\n            try:\n                interfaces: Any = interface_codes\n                if (\n                    isinstance(interfaces, dict) and\n                    contract_name in interfaces and\n                    isinstance(interfaces[contract_name], dict)\n                ):\n                    interfaces = interfaces[contract_name]\n                out.setdefault(contract_name, {})\n                out[contract_name][output_format] = output_formats_map[output_format](\n                    # trailing newline fixes python parsing bug when source ends in a comment\n                    # https://bugs.python.org/issue35107\n                    code=f\"{code}\\n\",\n                    contract_name=contract_name,\n                    interface_codes=interfaces,\n                    source_id=source_id\n                )\n            except Exception as exc:\n                if exc_handler is not None:\n                    exc_handler(contract_name, exc)\n                else:\n                    raise exc\n\n    return out\n\n\nUNKNOWN_CONTRACT_NAME = '<unknown>'\n\n\ndef compile_code(code, output_formats=None, interface_codes=None):\n    contract_sources = {UNKNOWN_CONTRACT_NAME: code}\n\n    return compile_codes(\n        contract_sources,\n        output_formats,\n        interface_codes=interface_codes,\n    )[UNKNOWN_CONTRACT_NAME]\n", "path": "vyper/compiler.py"}]}