Skip to content

Commit 0f2a8d1

Browse files
code print over lsp
1 parent 92c8caa commit 0f2a8d1

File tree

4 files changed

+28
-13
lines changed

4 files changed

+28
-13
lines changed

codeflash/cli_cmds/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def process_and_validate_cmd_args(args: Namespace) -> Namespace:
111111
from codeflash.code_utils.github_utils import require_github_app_or_exit
112112

113113
is_init: bool = args.command.startswith("init") if args.command else False
114-
if args.verbose or is_LSP_enabled():
114+
if args.verbose:
115115
logging_config.set_level(logging.DEBUG, echo_setting=not is_init)
116116
else:
117117
logging_config.set_level(logging.INFO, echo_setting=not is_init)

codeflash/cli_cmds/console.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from __future__ import annotations
22

3-
import json
43
import logging
54
from contextlib import contextmanager
65
from itertools import cycle
7-
from typing import TYPE_CHECKING, Any
6+
from typing import TYPE_CHECKING, Any, Optional
87

98
from rich.console import Console
109
from rich.logging import RichHandler
@@ -21,12 +20,15 @@
2120
from codeflash.cli_cmds.console_constants import SPINNER_TYPES
2221
from codeflash.cli_cmds.logging_config import BARE_LOGGING_FORMAT
2322
from codeflash.lsp.helpers import enhanced_log, is_LSP_enabled
23+
from codeflash.lsp.lsp_message import LspCodeMessage
2424

2525
if TYPE_CHECKING:
2626
from collections.abc import Generator
2727

2828
from rich.progress import TaskID
2929

30+
from codeflash.lsp.lsp_message import LspMessage
31+
3032
DEBUG_MODE = logging.getLogger().getEffectiveLevel() == logging.DEBUG
3133

3234
console = Console()
@@ -49,11 +51,11 @@
4951
setattr(logger, level, lambda msg, *args, _real_fn=real_fn, **kwargs: enhanced_log(msg, _real_fn, *args, **kwargs))
5052

5153

52-
def lsp_log(serializable: dict[str, Any], *args: Any, **kwargs: Any) -> None: # noqa: ANN401
54+
def lsp_log(message: LspMessage, *args: Any, **kwargs: Any) -> None: # noqa: ANN401
5355
if not is_LSP_enabled():
5456
return
55-
msg_str = json.dumps(serializable)
56-
logger.info(msg_str, *args, **kwargs)
57+
json_msg = message.serialize()
58+
logger.info(json_msg, *args, **kwargs)
5759

5860

5961
def paneled_text(
@@ -71,7 +73,10 @@ def paneled_text(
7173
console.print(panel)
7274

7375

74-
def code_print(code_str: str) -> None:
76+
def code_print(code_str: str, file_name: Optional[str] = None, function_name: Optional[str] = None) -> None:
77+
if is_LSP_enabled():
78+
lsp_log(LspCodeMessage(code=code_str, file_name=file_name, function_name=function_name))
79+
return
7580
"""Print code with syntax highlighting."""
7681
from rich.syntax import Syntax
7782

codeflash/lsp/lsp_message.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ def type(self) -> str:
3030

3131
def serialize(self) -> str:
3232
data = asdict(self)
33-
data["type"] = self.type()
34-
return json.dumps(data)
33+
# Important: keep type as the first key, for making it easy and fast for the client to know if this is a lsp message before parsing it
34+
ordered = {"type": self.type(), **data}
35+
return json.dumps(ordered)
3536

3637

3738
@dataclass
@@ -45,7 +46,7 @@ def type(self) -> str:
4546
@dataclass
4647
class LspCodeMessage(LspMessage):
4748
code: str
48-
path: Optional[Path] = None
49+
file_name: Optional[Path] = None
4950
function_name: Optional[str] = None
5051

5152
def type(self) -> str:
@@ -66,3 +67,8 @@ class LspStatsMessage(LspMessage):
6667

6768
def type(self) -> str:
6869
return "stats"
70+
71+
72+
if __name__ == "__main__":
73+
msg = LspTextMessage(text="Hello World")
74+
print(msg.serialize())

codeflash/optimization/function_optimizer.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ def generate_and_instrument_tests(
334334
)
335335
)
336336
logger.info(f"Generated test {i + 1}/{count_tests}:")
337-
code_print(generated_test.generated_original_test_source)
337+
code_print(generated_test.generated_original_test_source, file_name=f"test_{i + 1}.py")
338338
if concolic_test_str:
339339
logger.info(f"Generated test {count_tests}/{count_tests}:")
340340
code_print(concolic_test_str)
@@ -372,7 +372,11 @@ def optimize_function(self) -> Result[BestOptimization, str]:
372372

373373
should_run_experiment, code_context, original_helper_code = initialization_result.unwrap()
374374

375-
code_print(code_context.read_writable_code.flat)
375+
code_print(
376+
code_context.read_writable_code.flat,
377+
file_name=self.function_to_optimize.file_path,
378+
function_name=self.function_to_optimize.function_name,
379+
)
376380

377381
test_setup_result = self.generate_and_instrument_tests( # also generates optimizations
378382
code_context, should_run_experiment=should_run_experiment
@@ -496,7 +500,7 @@ def determine_best_candidate(
496500
get_run_tmp_file(Path(f"test_return_values_{candidate_index}.bin")).unlink(missing_ok=True)
497501
get_run_tmp_file(Path(f"test_return_values_{candidate_index}.sqlite")).unlink(missing_ok=True)
498502
logger.info(f"Optimization candidate {candidate_index}/{processor.candidate_len}:")
499-
code_print(candidate.source_code.flat)
503+
code_print(candidate.source_code.flat, file_name=f"candidate_{candidate_index}.py")
500504
# map ast normalized code to diff len, unnormalized code
501505
# map opt id to the shortest unnormalized code
502506
try:

0 commit comments

Comments
 (0)