Skip to content

Commit a867e42

Browse files
authored
Upgrade antlr to 4.11 (#2733)
1 parent 4db334b commit a867e42

File tree

12 files changed

+59
-19
lines changed

12 files changed

+59
-19
lines changed

.circleci/config.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ commands:
100100
name: Preparing environment - system
101101
command: |
102102
choco install -y --no-progress miniconda3
103-
choco install -y --no-progress openssl javaruntime
103+
choco install -y --no-progress openssl openjdk11jre
104104
C:\tools\miniconda3\Scripts\conda.exe init powershell
105105
- run:
106106
name: Preparing environment - Hydra

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ pip-wheel-metadata
1717
.ipynb_checkpoints
1818
/.dmypy.json
1919
TODO.txt
20+
/venv
3.38 MB
Binary file not shown.
-3.35 MB
Binary file not shown.

build_helpers/bin/antlr4

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import subprocess
44
import sys
55

66
my_dir = os.path.realpath(os.path.dirname(__file__))
7-
antlr = "antlr-4.9.3-complete.jar"
7+
antlr = "antlr-4.11.1-complete.jar"
88
args = ["java", "-jar", my_dir + "/" + antlr]
99
args.extend(sys.argv[1:])
1010
subprocess.check_call(args)

build_helpers/bin/grun

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import subprocess
44
import sys
55

66
my_dir = os.path.realpath(os.path.dirname(__file__))
7-
antlr = "antlr-4.9.3-complete.jar"
7+
antlr = "antlr-4.11.1-complete.jar"
88
args = ["java", "-cp", my_dir + "/" + antlr, "org.antlr.v4.gui.TestRig"]
99
args.extend(sys.argv[1:])
1010
subprocess.check_call(args)

build_helpers/build_helpers.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
import re
77
import shutil
88
import subprocess
9+
from functools import partial
910
from os.path import abspath, basename, dirname, exists, isdir, join
11+
from pathlib import Path
1012
from typing import List, Optional
1113

1214
from setuptools import Command
@@ -185,7 +187,7 @@ def run(self) -> None:
185187
command = [
186188
"java",
187189
"-jar",
188-
join(root_dir, "bin/antlr-4.9.3-complete.jar"),
190+
join(root_dir, "bin/antlr-4.11.1-complete.jar"),
189191
"-Dlanguage=Python3",
190192
"-o",
191193
join(project_root, "hydra/grammar/gen/"),
@@ -198,8 +200,37 @@ def run(self) -> None:
198200

199201
subprocess.check_call(command)
200202

203+
log.info("Replacing imports of antlr4 in generated parsers")
204+
self._fix_imports()
205+
201206
def initialize_options(self) -> None:
202207
pass
203208

204209
def finalize_options(self) -> None:
205210
pass
211+
212+
def _fix_imports(self) -> None:
213+
"""Fix imports from the generated parsers to use the vendored antlr4 instead"""
214+
build_dir = Path(__file__).parent.absolute()
215+
project_root = build_dir.parent
216+
lib = "antlr4"
217+
pkgname = 'omegaconf.vendor'
218+
219+
replacements = [
220+
partial( # import antlr4 -> import omegaconf.vendor.antlr4
221+
re.compile(r'(^\s*)import {}\n'.format(lib), flags=re.M).sub,
222+
r'\1from {} import {}\n'.format(pkgname, lib)
223+
),
224+
partial( # from antlr4 -> from fomegaconf.vendor.antlr4
225+
re.compile(r'(^\s*)from {}(\.|\s+)'.format(lib), flags=re.M).sub,
226+
r'\1from {}.{}\2'.format(pkgname, lib)
227+
),
228+
]
229+
230+
path = project_root / "hydra" / "grammar" / "gen"
231+
for item in path.iterdir():
232+
if item.is_file() and item.name.endswith(".py"):
233+
text = item.read_text('utf8')
234+
for replacement in replacements:
235+
text = replacement(text)
236+
item.write_text(text, 'utf8')

hydra/core/override_parser/overrides_parser.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
import sys
33
from typing import Any, List, Optional
44

5-
from antlr4.error.Errors import LexerNoViableAltException, RecognitionException
5+
from omegaconf.vendor.antlr4.error.Errors import (
6+
LexerNoViableAltException,
7+
RecognitionException,
8+
)
69

710
from hydra._internal.grammar import grammar_functions
811
from hydra._internal.grammar.functions import Functions

hydra/core/override_parser/overrides_visitor.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
import warnings
44
from typing import Any, Dict, List, Optional, Tuple, Union
55

6-
from antlr4 import ParserRuleContext, TerminalNode, Token
7-
from antlr4.error.ErrorListener import ErrorListener
8-
from antlr4.tree.Tree import TerminalNodeImpl
6+
from omegaconf.vendor.antlr4 import ( # type: ignore[attr-defined]
7+
ParserRuleContext,
8+
TerminalNode,
9+
Token,
10+
)
11+
from omegaconf.vendor.antlr4.error.ErrorListener import ErrorListener
12+
from omegaconf.vendor.antlr4.tree.Tree import TerminalNodeImpl
913

1014
from hydra._internal.grammar.functions import FunctionCall, Functions
1115
from hydra._internal.grammar.utils import _ESC_QUOTED_STR
@@ -162,7 +166,7 @@ def visitOverride(self, ctx: OverrideParser.OverrideContext) -> Override:
162166
if (
163167
override_type == OverrideType.DEL
164168
and isinstance(eq_node, TerminalNode)
165-
and eq_node.symbol.type == Token.EOF
169+
and eq_node.symbol.type == Token.EOF # type: ignore[attr-defined]
166170
):
167171
value = None
168172
value_type = None
@@ -244,26 +248,26 @@ def visitFunction(self, ctx: OverrideParser.FunctionContext) -> Any:
244248
) from e
245249

246250
def _createPrimitive(
247-
self, ctx: ParserRuleContext
251+
self, ctx: ParserRuleContext # type: ignore[valid-type]
248252
) -> Optional[Union[QuotedString, int, bool, float, str]]:
249253
ret: Optional[Union[int, bool, float, str]]
250254
first_idx = 0
251-
last_idx = ctx.getChildCount()
255+
last_idx = ctx.getChildCount() # type: ignore[attr-defined]
252256
# skip first if whitespace
253-
if self.is_ws(ctx.getChild(0)):
257+
if self.is_ws(ctx.getChild(0)): # type: ignore[attr-defined]
254258
if last_idx == 1:
255259
# Only whitespaces => this is not allowed.
256260
raise HydraException(
257261
"Trying to parse a primitive that is all whitespaces"
258262
)
259263
first_idx = 1
260-
if self.is_ws(ctx.getChild(-1)):
264+
if self.is_ws(ctx.getChild(-1)): # type: ignore[attr-defined]
261265
last_idx = last_idx - 1
262266
num = last_idx - first_idx
263267
if num > 1:
264268
# Concatenate, while un-escaping as needed.
265269
tokens = []
266-
for i, n in enumerate(ctx.getChildren()):
270+
for i, n in enumerate(ctx.getChildren()): # type: ignore[attr-defined]
267271
if n.symbol.type == OverrideLexer.WS and (
268272
i < first_idx or i >= last_idx
269273
):
@@ -276,7 +280,7 @@ def _createPrimitive(
276280
)
277281
ret = "".join(tokens)
278282
else:
279-
node = ctx.getChild(first_idx)
283+
node = ctx.getChild(first_idx) # type: ignore[attr-defined]
280284
if node.symbol.type == OverrideLexer.QUOTED_VALUE:
281285
text = node.getText()
282286
qc = text[0]
@@ -360,7 +364,7 @@ def _unescape_quoted_string(self, text: str) -> str:
360364
return "".join(tokens)
361365

362366

363-
class HydraErrorListener(ErrorListener): # type: ignore
367+
class HydraErrorListener(ErrorListener):
364368
def syntaxError(
365369
self,
366370
recognizer: Any,

hydra/core/plugins.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,14 @@ def _scan_all_plugins(
187187
assert m is not None
188188
loaded_mod = m.load_module(modname)
189189
else:
190-
spec = importer.find_spec(modname)
190+
spec = importer.find_spec(modname) # type: ignore[call-arg]
191191
assert spec is not None
192192
if modname in sys.modules:
193193
loaded_mod = sys.modules[modname]
194194
else:
195195
loaded_mod = importlib.util.module_from_spec(spec)
196196
if loaded_mod is not None:
197+
assert spec.loader is not None
197198
spec.loader.exec_module(loaded_mod)
198199
sys.modules[modname] = loaded_mod
199200

0 commit comments

Comments
 (0)