Skip to content

Commit 29ad498

Browse files
committed
SRC: enable lazy loading
1 parent db2207b commit 29ad498

File tree

1 file changed

+31
-25
lines changed

1 file changed

+31
-25
lines changed

chc/source/CSrcFile.py

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
# The MIT License (MIT)
66
#
77
# Copyright (c) 2017-2020 Kestrel Technology LLC
8+
# Copyright (c) 2020-2023 Henny B. Sipma
9+
# Copyright (c) 2024 Aarno Labs LLC
810
#
911
# Permission is hereby granted, free of charge, to any person obtaining a copy
1012
# of this software and associated documentation files (the "Software"), to deal
@@ -29,45 +31,49 @@
2931
from typing import Dict, TYPE_CHECKING, Optional
3032

3133
import chc.util.fileutil as UF
34+
from chc.util.loggingutil import chklogger
3235

3336
if TYPE_CHECKING:
34-
import chc.app.CApplication
37+
from chc.app.CApplication import CApplication
3538

3639

3740
class CSrcFile:
3841
"""Represents the text file that holds the C source code."""
3942

40-
def __init__(self, capp: "chc.app.CApplication.CApplication", fname: str) -> None:
41-
self.capp = capp
42-
self.fname = fname
43-
self._lines: Dict[int, str] = {}
44-
if not self.fname.endswith(".c"):
45-
self.fname = fname + ".c"
43+
def __init__(self, capp: "CApplication", fname: str) -> None:
44+
self._capp = capp
45+
self._fname = fname
46+
self._lines: Optional[Dict[int, str]] = None
47+
48+
@property
49+
def capp(self) -> "CApplication":
50+
return self._capp
51+
52+
@property
53+
def fname(self) -> str:
54+
"""Returns the absolute c filename relative to the project directory."""
55+
56+
return self._fname
4657

4758
@property
4859
def lines(self) -> Dict[int, str]:
49-
if len(self._lines) == 0:
50-
self._initialize()
60+
if self._lines is None:
61+
self._lines = {}
62+
if os.path.isfile(self.fname):
63+
n: int = 1
64+
with open(self.fname) as fp:
65+
for line in fp:
66+
self._lines[n] = line
67+
n += 1
68+
else:
69+
chklogger.logger.warning(
70+
"Source file %s not found", self.fname)
5171
return self._lines
5272

5373
def get_line_count(self) -> int:
54-
return sum(1 for line in open(self.fname))
74+
return len(self.lines)
5575

5676
def get_line(self, n: int) -> Optional[str]:
57-
self._initialize()
58-
if n <= len(self.lines):
77+
if self.get_line_count() > n:
5978
return str(n) + " " + self.lines[n]
6079
return None
61-
62-
def _initialize(self) -> None:
63-
if len(self._lines) > 0:
64-
return
65-
if os.path.isfile(self.fname):
66-
print("Reading file " + self.fname)
67-
n = 1
68-
with open(self.fname) as f:
69-
for line in f:
70-
self._lines[n] = line
71-
n += 1
72-
else:
73-
print("Source file " + self.fname + " not found")

0 commit comments

Comments
 (0)