forked from google/swift-jupyter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswift_kernel.py
More file actions
executable file
·3528 lines (3001 loc) · 142 KB
/
swift_kernel.py
File metadata and controls
executable file
·3528 lines (3001 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import json
import os
import sys
# Add LLDB Python path if PYTHONPATH is set (from kernel.json env)
if 'PYTHONPATH' in os.environ and os.environ['PYTHONPATH'] not in sys.path:
sys.path.insert(0, os.environ['PYTHONPATH'])
# import lldb # Moved to lazy import
import stat
import re
import shlex
import shutil
import signal
import string
import subprocess
import sys
import tempfile
import textwrap
import time
import threading
import sqlite3
import json
import tempfile
import logging
from lsp_client import LSPClient
from ipykernel.kernelbase import Kernel
from jupyter_client.jsonutil import squash_dates
from tornado import ioloop
class ExecutionResult:
"""Base class for the result of executing code."""
pass
class ExecutionResultSuccess(ExecutionResult):
"""Base class for the result of successfully executing code."""
pass
class ExecutionResultError(ExecutionResult):
"""Base class for the result of unsuccessfully executing code."""
def description(self):
raise NotImplementedError()
class SuccessWithoutValue(ExecutionResultSuccess):
"""The code executed successfully, and did not produce a value."""
def __repr__(self):
return 'SuccessWithoutValue()'
class SuccessWithValue(ExecutionResultSuccess):
"""The code executed successfully, and produced a value."""
def __init__(self, result):
self.result = result # SBValue
"""A description of the value, e.g.
(Int) $R0 = 64"""
def value_description(self):
stream = lldb.SBStream()
self.result.GetDescription(stream)
return stream.GetData()
def get_formatted_value(self):
"""Get a nicely formatted value for display in notebooks.
Returns a string suitable for showing to users, extracting just the
value part without LLDB metadata like variable names.
Examples:
(Int) $R0 = 42 -> "42"
(String) $R1 = "hello" -> "hello"
(Array<Int>) $R2 = [1, 2, 3] -> [1, 2, 3]
"""
# First, try to get the full description which has the most complete info
full_desc = self.value_description()
# Try to extract just the value after the '='
if '=' in full_desc:
value_part = full_desc.split('=', 1)[1].strip()
return value_part
# For types without '=' (shouldn't happen often), try summary/value
summary_str = self.result.GetSummary()
if summary_str:
# Remove quotes around the summary if present (LLDB adds them for strings)
summary = summary_str.strip('"')
return summary
value_str = self.result.GetValue()
if value_str:
return value_str
# Last resort: return the full description
return full_desc
def get_rich_display(self):
"""Get rich display data including HTML for arrays, dictionaries, and tables.
Returns a tuple of (plain_text, html_or_image) where the second element
may be None if no rich display is available, or a dict with image data.
"""
import html as html_module
plain_text = self.get_formatted_value()
type_name = self.result.GetTypeName() or ""
# Check if this is Data that might be an image
if self._is_image_data(type_name):
image_data = self._get_image_data()
if image_data:
# Return as a special marker for image display
return (plain_text, {'__image__': image_data})
# Check if this is an array type
if self._is_array_type(type_name):
html = self._render_array_html()
if html:
return (plain_text, html)
# Check if this is a dictionary type
if self._is_dictionary_type(type_name):
html = self._render_dictionary_html()
if html:
return (plain_text, html)
# Check if this might be a struct/class with multiple fields
num_children = self.result.GetNumChildren()
if num_children > 0 and num_children <= 50:
# Could be a struct, class, tuple, or collection
html = self._render_object_html()
if html:
return (plain_text, html)
return (plain_text, None)
def _is_array_type(self, type_name):
"""Check if the type is an array."""
return ('Array<' in type_name or
'ContiguousArray<' in type_name or
'ArraySlice<' in type_name or
type_name.startswith('[') and type_name.endswith(']'))
def _is_dictionary_type(self, type_name):
"""Check if the type is a dictionary."""
return ('Dictionary<' in type_name or
'type_name'.startswith('[') and ':' in type_name)
def _is_image_data(self, type_name):
"""Check if this might be image data."""
# Look for Foundation.Data or Swift Data type
return 'Data' in type_name or 'NSData' in type_name
def _get_image_data(self):
"""Try to extract image data and return it as base64.
Returns a dict with 'data' and 'mime_type' keys, or None if not an image.
"""
import base64
# Try to get the bytes from the Data object
# This is challenging because LLDB doesn't give us direct byte access
# We'll try to detect common image signatures
# Get the count/length of the data
count_child = self.result.GetChildMemberWithName('count')
if not count_child:
# Try _count for internal representation
count_child = self.result.GetChildMemberWithName('_count')
if not count_child:
return None
count = count_child.GetValueAsUnsigned(0)
# Images should be at least a few bytes
if count < 8 or count > 10 * 1024 * 1024: # Max 10MB
return None
# Unfortunately, getting raw bytes from LLDB's SBValue is complex
# For now, we'll return None - full implementation would require
# executing Swift code to convert Data to base64 string
return None
def _render_array_html(self):
"""Render an array as an HTML table."""
import html as html_module
num_children = self.result.GetNumChildren()
if num_children == 0:
return '<div style="font-family: monospace; padding: 8px; background: #f8f9fa; border-radius: 4px;">[]</div>'
if num_children > 100:
# Too large, don't render as HTML
return None
rows = []
for i in range(num_children):
child = self.result.GetChildAtIndex(i)
value = child.GetValue() or child.GetSummary() or str(child)
# Clean up the value
if value:
value = html_module.escape(str(value).strip('"'))
else:
value = "nil"
rows.append(f'<tr><td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6; color: #6c757d;">{i}</td><td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6;">{value}</td></tr>')
html = f'''
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<div style="color: #6c757d; font-size: 12px; margin-bottom: 4px;">Array ({num_children} elements)</div>
<table style="border-collapse: collapse; border: 1px solid #dee2e6; background: white;">
<thead>
<tr style="background: #f8f9fa;">
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Index</th>
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Value</th>
</tr>
</thead>
<tbody>
{''.join(rows)}
</tbody>
</table>
</div>
'''
return html
def _render_dictionary_html(self):
"""Render a dictionary as an HTML table."""
import html as html_module
num_children = self.result.GetNumChildren()
if num_children == 0:
return '<div style="font-family: monospace; padding: 8px; background: #f8f9fa; border-radius: 4px;">[:]</div>'
if num_children > 100:
return None
rows = []
for i in range(num_children):
child = self.result.GetChildAtIndex(i)
# Dictionary entries have key and value children
key_child = child.GetChildMemberWithName('key')
value_child = child.GetChildMemberWithName('value')
if key_child and value_child:
key = key_child.GetValue() or key_child.GetSummary() or str(key_child)
value = value_child.GetValue() or value_child.GetSummary() or str(value_child)
else:
# Fallback: use child directly
key = str(i)
value = child.GetValue() or child.GetSummary() or str(child)
key = html_module.escape(str(key).strip('"'))
value = html_module.escape(str(value).strip('"'))
rows.append(f'<tr><td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6; font-weight: 500;">{key}</td><td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6;">{value}</td></tr>')
html = f'''
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<div style="color: #6c757d; font-size: 12px; margin-bottom: 4px;">Dictionary ({num_children} entries)</div>
<table style="border-collapse: collapse; border: 1px solid #dee2e6; background: white;">
<thead>
<tr style="background: #f8f9fa;">
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Key</th>
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Value</th>
</tr>
</thead>
<tbody>
{''.join(rows)}
</tbody>
</table>
</div>
'''
return html
def _render_object_html(self):
"""Render a struct/class/tuple as an HTML table of properties."""
import html as html_module
type_name = self.result.GetTypeName() or "Object"
num_children = self.result.GetNumChildren()
if num_children == 0:
return None
# Skip if it looks like a simple wrapper
if num_children == 1:
return None
rows = []
for i in range(num_children):
child = self.result.GetChildAtIndex(i)
name = child.GetName() or f"[{i}]"
child_type = child.GetTypeName() or ""
value = child.GetValue() or child.GetSummary() or ""
# Clean up values
name = html_module.escape(str(name))
value = html_module.escape(str(value).strip('"')) if value else "<nil>"
child_type = html_module.escape(str(child_type))
rows.append(f'''<tr>
<td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6; font-weight: 500;">{name}</td>
<td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6; color: #6c757d; font-size: 12px;">{child_type}</td>
<td style="padding: 4px 12px; border-bottom: 1px solid #dee2e6;">{value}</td>
</tr>''')
# Clean up type name for display
display_type = html_module.escape(type_name.split('.')[-1])
html = f'''
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<div style="color: #6c757d; font-size: 12px; margin-bottom: 4px;">{display_type}</div>
<table style="border-collapse: collapse; border: 1px solid #dee2e6; background: white;">
<thead>
<tr style="background: #f8f9fa;">
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Property</th>
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Type</th>
<th style="padding: 8px 12px; border-bottom: 2px solid #dee2e6; text-align: left;">Value</th>
</tr>
</thead>
<tbody>
{''.join(rows)}
</tbody>
</table>
</div>
'''
return html
def __repr__(self):
return 'SuccessWithValue(result=%s, description=%s)' % (
repr(self.result), repr(self.result.description))
class PreprocessorError(ExecutionResultError):
"""There was an error preprocessing the code."""
def __init__(self, exception):
self.exception = exception # PreprocessorException
def description(self):
return str(self.exception)
def __repr__(self):
return 'PreprocessorError(exception=%s)' % repr(self.exception)
class PreprocessorException(Exception):
pass
class PackageInstallException(Exception):
pass
class SwiftError(ExecutionResultError):
"""There was a compile or runtime error (R5-T3 enhanced).
This class now provides better error formatting including:
- Structured error information
- Error type detection
- Cleaned error messages
- Better Unicode handling in error text
"""
def __init__(self, result):
self.result = result # SBValue
self._parsed_error = None
def description(self):
"""Get error description with improved formatting."""
error_desc = self.result.error.description
# Decode if bytes (shouldn't happen in Python 3, but be safe)
if isinstance(error_desc, bytes):
error_desc = error_desc.decode('utf-8', errors='replace')
return error_desc
def get_error_type(self):
"""Extract error type from LLDB error.
Returns:
str: Error type like 'error', 'warning', 'note', or 'unknown'
"""
desc = self.description()
if 'error:' in desc.lower():
return 'error'
elif 'warning:' in desc.lower():
return 'warning'
elif 'note:' in desc.lower():
return 'note'
return 'unknown'
def get_cleaned_message(self):
"""Get a cleaned, more readable error message.
Removes LLDB-specific noise and formats the message better.
"""
desc = self.description()
# Remove common LLDB prefixes
prefixes_to_remove = [
'error: <EXPR>:',
'Execution was interrupted, reason: ',
]
for prefix in prefixes_to_remove:
if desc.startswith(prefix):
desc = desc[len(prefix):].lstrip()
return desc.strip()
def get_helpful_message(self):
"""Get an enhanced error message with helpful suggestions.
Analyzes common Swift error patterns and adds actionable advice.
Returns:
str: Enhanced error message with suggestions and tips
"""
original_error = self.get_cleaned_message()
suggestions = []
# Pattern 1: Cannot assign to immutable variable
if "cannot assign to value:" in original_error.lower() and "is a 'let' constant" in original_error.lower():
# Extract variable name if possible
import re
match = re.search(r"'(\w+)' is a 'let' constant", original_error)
if match:
var_name = match.group(1)
suggestions.append(f"💡 Tip: Change 'let {var_name}' to 'var {var_name}' to make it mutable")
else:
suggestions.append("💡 Tip: Use 'var' instead of 'let' to declare mutable variables")
suggestions.append("📖 Learn more: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID310")
# Pattern 2: Use of undeclared identifier
elif "use of unresolved identifier" in original_error.lower() or "use of undeclared identifier" in original_error.lower():
import re
match = re.search(r"identifier '(\w+)'", original_error)
if match:
var_name = match.group(1)
suggestions.append(f"💡 Tip: Make sure '{var_name}' is defined before using it")
suggestions.append(" • Check for typos in the variable name")
suggestions.append(" • Ensure the variable was declared in a previous cell")
else:
suggestions.append("💡 Tip: Make sure the identifier is defined before using it")
# Pattern 3: Type mismatch
elif "cannot convert value of type" in original_error.lower():
suggestions.append("💡 Tip: Check the types of your values")
suggestions.append(" • You may need to convert between types explicitly")
suggestions.append(" • Example: String(intValue) or Int(stringValue)")
# Pattern 4: Missing return statement
elif "missing return" in original_error.lower():
suggestions.append("💡 Tip: All code paths in this function must return a value")
suggestions.append(" • Add a return statement to every branch (if/else, switch cases)")
suggestions.append(" • Or use 'return' with a default value at the end")
# Pattern 5: Optional unwrapping
elif "value of optional type" in original_error.lower() and ("must be unwrapped" in original_error.lower() or "not unwrapped" in original_error.lower()):
# Check if Swift compiler already provided suggestions (it often does)
if "coalesce using '??'" not in original_error and "force-unwrap using '!'" not in original_error:
suggestions.append("💡 Tip: Optional values must be unwrapped before use")
suggestions.append(" • Safe unwrapping: if let value = optional { ... }")
suggestions.append(" • Guard: guard let value = optional else { return }")
suggestions.append(" • Nil coalescing: optional ?? defaultValue")
suggestions.append(" • Force unwrap (risky): optional! - only if you're certain it's not nil")
suggestions.append("📖 Learn more: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330")
# Pattern 6: Nil coalescing
elif "unexpectedly found nil" in original_error.lower():
suggestions.append("💡 Tip: An optional value was nil when it shouldn't be")
suggestions.append(" • Use nil coalescing: value ?? defaultValue")
suggestions.append(" • Or check for nil: if value != nil { ... }")
# Pattern 7: Cannot call value of non-function type
elif "cannot call value of non-function type" in original_error.lower():
suggestions.append("💡 Tip: You're trying to call something that isn't a function")
suggestions.append(" • Check that you're using () on functions, not properties")
suggestions.append(" • Make sure the function name is spelled correctly")
# Pattern 8: Consecutive statements on a line
elif "consecutive statements on a line must be separated by" in original_error.lower():
suggestions.append("💡 Tip: Put each statement on its own line or separate with semicolons")
suggestions.append(" • Each statement should be on a new line")
suggestions.append(" • Or use semicolons: let x = 1; let y = 2")
# Pattern 9: Expected expression
elif "expected expression" in original_error.lower():
suggestions.append("💡 Tip: Swift expected a value or expression here")
suggestions.append(" • Check for missing values after operators")
suggestions.append(" • Make sure all parentheses and brackets are balanced")
# Pattern 10: Initializer requires arguments
elif "missing argument" in original_error.lower() or "requires that" in original_error.lower():
suggestions.append("💡 Tip: This initializer or function needs more arguments")
suggestions.append(" • Check the function signature to see what parameters are required")
suggestions.append(" • Provide all required arguments or use default values")
# Build the final message
if suggestions:
return original_error + "\n\n" + "\n".join(suggestions)
else:
# No specific suggestion - just return the error
# The Swift compiler often provides good suggestions already
return original_error
def __repr__(self):
return 'SwiftError(type=%s, description=%s)' % (
self.get_error_type(), repr(self.get_cleaned_message()))
class SIGINTHandler(threading.Thread):
"""Interrupts currently-executing code whenever the process receives a
SIGINT (R5-T2 enhanced).
This handler works in conjunction with the message-based interrupt handler
(interrupt_request) from R3. Both mechanisms are supported:
- Signal-based (SIGINT): For backward compatibility and old Jupyter clients
- Message-based: For Protocol 5.4+ clients (see interrupt_request method)
The handler now includes:
- Interrupt flag tracking
- Better logging
- Exception handling
"""
daemon = True
def __init__(self, kernel):
super(SIGINTHandler, self).__init__()
self.kernel = kernel
self.interrupted = False
self.interrupt_count = 0
def run(self):
try:
while True:
signal.sigwait([signal.SIGINT])
self.interrupt_count += 1
self.interrupted = True
self.kernel.log.info(
f'🛑 SIGINTHandler: Received SIGINT (count: {self.interrupt_count})')
if not self.kernel.process or not self.kernel.process.IsValid():
self.kernel.log.warning(
'SIGINTHandler: No valid process to interrupt')
continue
try:
self.kernel.process.SendAsyncInterrupt()
self.kernel.log.info('SIGINTHandler: Sent async interrupt to LLDB')
except Exception as interrupt_error:
self.kernel.log.error(
f'SIGINTHandler: Failed to interrupt: {interrupt_error}')
except Exception as e:
self.kernel.log.error(f'Exception in SIGINTHandler: {e}', exc_info=True)
class StdoutHandler(threading.Thread):
"""Collects stdout from the Swift process and sends it to the client."""
daemon = True
def __init__(self, kernel):
super(StdoutHandler, self).__init__()
self.kernel = kernel
self.stop_event = threading.Event()
self.had_stdout = False
def _get_stdout(self):
"""Get stdout from LLDB process with Unicode handling (R5-T1)."""
while True:
BUFFER_SIZE = 1000
stdout_buffer = self.kernel.process.GetSTDOUT(BUFFER_SIZE)
if len(stdout_buffer) == 0:
break
# LLDB returns bytes; decode to Unicode string
# Use 'replace' error handling to avoid crashes on invalid UTF-8
if isinstance(stdout_buffer, bytes):
try:
stdout_buffer = stdout_buffer.decode('utf-8', errors='replace')
except Exception as e:
self.kernel.log.warning(f'Error decoding stdout: {e}')
# Fallback to latin-1 which never fails
stdout_buffer = stdout_buffer.decode('latin-1')
yield stdout_buffer
# Sends stdout to the jupyter client, replacing the ANSI sequence for
# clearing the whole display with a 'clear_output' message to the jupyter
# client.
def _send_stdout(self, stdout):
clear_sequence = '\033[2J'
clear_sequence_index = stdout.find(clear_sequence)
if clear_sequence_index != -1:
self._send_stdout(stdout[:clear_sequence_index])
self.kernel.send_response(
self.kernel.iopub_socket, 'clear_output', {'wait': False})
self._send_stdout(
stdout[clear_sequence_index + len(clear_sequence):])
else:
self.kernel.send_response(self.kernel.iopub_socket, 'stream', {
'name': 'stdout',
'text': stdout
})
def _get_and_send_stdout(self):
stdout = ''.join([buf for buf in self._get_stdout()])
if len(stdout) > 0:
self.had_stdout = True
self._send_stdout(stdout)
def run(self):
try:
while True:
if self.stop_event.wait(0.1):
break
self._get_and_send_stdout()
self._get_and_send_stdout()
except Exception as e:
self.kernel.log.error('Exception in StdoutHandler: %s' % str(e))
# =============================================================================
# SwiftIR Directives Mixin - Pre-compiled Library Support
# Added by integrate_swiftir.py
# =============================================================================
class SwiftIRDirectivesMixin:
"""
Mixin class providing pre-compiled library support directives.
Adds support for:
- %swift_flags: Add custom compiler flags
- %swift_library_path: Add to LD_LIBRARY_PATH
- %swift_module_path: Add Swift module search paths
- %swift_env: Set environment variables
- %swift_link: Link specific libraries
- %swiftir_setup: One-line SwiftIR SDK setup
- %swift_framework_path: Add framework search paths (macOS)
- %swift_config: Show current configuration
"""
def _init_swiftir_directives(self):
"""Initialize SwiftIR directive state. Called from __init__."""
self.custom_swift_flags = []
self.custom_library_paths = []
self.custom_module_paths = []
self.custom_framework_paths = []
self.custom_env_vars = {}
def _process_swiftir_directive(self, code):
"""Check if code contains a SwiftIR directive and process it."""
stripped = code.strip()
match = re.match(r'^%swiftir_setup\s+(.+)$', stripped)
if match:
self._handle_swiftir_setup(match.group(1))
return (True, '')
match = re.match(r'^%swift_flags\s+(.+)$', stripped, re.DOTALL)
if match:
self._handle_swift_flags(match.group(1))
return (True, '')
match = re.match(r'^%swift_library_path\s+(.+)$', stripped)
if match:
self._handle_swift_library_path(match.group(1))
return (True, '')
match = re.match(r'^%swift_module_path\s+(.+)$', stripped)
if match:
self._handle_swift_module_path(match.group(1))
return (True, '')
match = re.match(r'^%swift_env\s+(.+)$', stripped)
if match:
self._handle_swift_env(match.group(1))
return (True, '')
match = re.match(r'^%swift_link\s+(.+)$', stripped)
if match:
self._handle_swift_link(match.group(1))
return (True, '')
match = re.match(r'^%swift_framework_path\s+(.+)$', stripped)
if match:
self._handle_swift_framework_path(match.group(1))
return (True, '')
if stripped == '%swift_config':
self._handle_swift_config()
return (True, '')
return (False, None)
def _handle_swift_flags(self, flags_str):
"""Handle %swift_flags directive."""
try:
flags = shlex.split(flags_str)
for i, flag in enumerate(flags):
self.custom_swift_flags.append(flag)
if flag.startswith('-I') and len(flag) > 2:
path = flag[2:]
if os.path.isdir(path):
self._add_custom_module_path(path)
if flag.startswith('-L') and len(flag) > 2:
path = flag[2:]
if os.path.isdir(path):
self._add_custom_library_path(path)
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Added compiler flags: {" ".join(flags)}\n'
})
except Exception as e:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'❌ Error parsing swift_flags: {e}\n'
})
def _handle_swift_library_path(self, path_str):
"""Handle %swift_library_path directive."""
paths = path_str.strip().split(':')
added = []
for path in paths:
path = os.path.expanduser(path.strip())
if not path:
continue
if os.path.isdir(path):
self._add_custom_library_path(path)
added.append(path)
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'⚠️ Path does not exist: {path}\n'
})
if added:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Added library paths: {":".join(added)}\n'
})
def _handle_swift_module_path(self, path_str):
"""Handle %swift_module_path directive."""
paths = path_str.strip().split(':')
added = []
for path in paths:
path = os.path.expanduser(path.strip())
if not path:
continue
if os.path.isdir(path):
self._add_custom_module_path(path)
added.append(path)
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'⚠️ Path does not exist: {path}\n'
})
if added:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Added module paths: {":".join(added)}\n'
})
def _handle_swift_env(self, env_str):
"""Handle %swift_env directive."""
if '=' not in env_str:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': '❌ Invalid format. Use: %swift_env NAME=value\n'
})
return
try:
name, value = env_str.strip().split('=', 1)
name = name.strip()
value = os.path.expanduser(value.strip())
self.custom_env_vars[name] = value
os.environ[name] = value
if hasattr(self, 'debugger') and self.debugger:
self.debugger.HandleCommand(f'settings append target.env-vars {name}={value}')
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Set environment: {name}={value}\n'
})
except Exception as e:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'❌ Error setting environment: {e}\n'
})
def _handle_swift_link(self, lib_str):
"""Handle %swift_link directive."""
libs = lib_str.strip().split()
for lib in libs:
if lib.startswith('-l'):
self.custom_swift_flags.append(lib)
else:
self.custom_swift_flags.append(f'-l{lib}')
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Added libraries: {" ".join(libs)}\n'
})
def _handle_swift_framework_path(self, path_str):
"""Handle %swift_framework_path directive (macOS)."""
paths = path_str.strip().split(':')
added = []
for path in paths:
path = os.path.expanduser(path.strip())
if not path:
continue
if os.path.isdir(path):
path = os.path.abspath(path)
if path not in self.custom_framework_paths:
self.custom_framework_paths.append(path)
self.custom_swift_flags.extend(['-F', path])
if hasattr(self, 'debugger') and self.debugger:
self.debugger.HandleCommand(
f'settings append target.swift-framework-search-paths "{path}"')
added.append(path)
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'⚠️ Path does not exist: {path}\n'
})
if added:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'✅ Added framework paths: {":".join(added)}\n'
})
def _handle_swiftir_setup(self, sdk_path):
"""Handle %swiftir_setup convenience directive."""
sdk_path = os.path.expanduser(sdk_path.strip())
if not os.path.isdir(sdk_path):
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f'❌ SDK path does not exist: {sdk_path}\n'
})
return
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f'🔧 Setting up SwiftIR SDK from: {sdk_path}\n'
})
lib_path = os.path.join(sdk_path, 'lib')
if os.path.isdir(lib_path):
self._add_custom_library_path(lib_path)
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 📚 Library path: {lib_path}\n'
})
for mod_dir in ['swift-modules', 'modules']:
mod_path = os.path.join(sdk_path, mod_dir)
if os.path.isdir(mod_path):
self._add_custom_module_path(mod_path)
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 📦 Module path: {mod_path}\n'
})
inc_path = os.path.join(sdk_path, 'include')
if os.path.isdir(inc_path):
self.custom_swift_flags.extend(['-I', inc_path])
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 📁 Include path: {inc_path}\n'
})
self.custom_env_vars['SWIFTIR_HOME'] = sdk_path
os.environ['SWIFTIR_HOME'] = sdk_path
if hasattr(self, 'debugger') and self.debugger:
self.debugger.HandleCommand(f'settings append target.env-vars SWIFTIR_HOME={sdk_path}')
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 🌍 SWIFTIR_HOME={sdk_path}\n'
})
# Load dynamic libraries if present
lib_path = os.path.join(sdk_path, 'lib')
dynamic_libs_loaded = []
if os.path.isdir(lib_path):
# Look for SwiftIR dynamic libraries
for lib_name in ['libSwiftIRRuntimeDynamic.so', 'libSwiftIR.so']:
lib_file = os.path.join(lib_path, lib_name)
if os.path.isfile(lib_file):
# Determine dlopen module based on platform
import platform
dlopen_module = 'Darwin' if platform.system() == 'Darwin' else 'Glibc'
dlopen_code = f'''
import func {dlopen_module}.dlopen
import var {dlopen_module}.RTLD_NOW
dlopen("{lib_file}", RTLD_NOW)
'''
result = self._execute(dlopen_code)
if isinstance(result, SuccessWithValue):
dynamic_libs_loaded.append(lib_name)
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 🔗 Loaded: {lib_name}\n'
})
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f' ⚠️ Failed to load {lib_name}\n'
})
# Try to compile SwiftIRRuntime sources if available (more reliable than pre-built modules)
sources_compiled = False
sources_path = os.path.join(sdk_path, 'swift-sources', 'SwiftIRRuntime')
if os.path.isdir(sources_path):
# Find all .swift files
swift_files = sorted([f for f in os.listdir(sources_path) if f.endswith('.swift')])
if swift_files:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': f' 📝 Compiling SwiftIRRuntime sources ({len(swift_files)} files)...\n'
})
# Read and execute each source file
all_sources = []
for swift_file in swift_files:
file_path = os.path.join(sources_path, swift_file)
try:
with open(file_path, 'r') as f:
content = f.read()
# Skip the file's import Foundation if we already have it
all_sources.append(content)
except Exception as e:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f' ⚠️ Failed to read {swift_file}: {e}\n'
})
# Compile all sources together
if all_sources:
combined_source = '\n'.join(all_sources)
result = self._execute(combined_source)
if isinstance(result, SuccessWithValue) or (hasattr(result, 'result') and result.result is None):
sources_compiled = True
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': ' ✅ SwiftIRRuntime compiled successfully!\n'
})
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stderr',
'text': f' ⚠️ Compilation had issues (types may still be available)\n'
})
if sources_compiled:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': '✅ SwiftIR SDK ready! Use: RuntimeDetector.detect(), AcceleratorType.cpu, etc.\n'
})
elif dynamic_libs_loaded:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': '✅ SwiftIR SDK configured! You can now `import SwiftIRRuntime`\n'
})
else:
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': '✅ SwiftIR SDK configured (module paths set).\n'
})
self.send_response(self.iopub_socket, 'stream', {
'name': 'stdout',
'text': ' 💡 Note: For full REPL support, include swift-sources/ or libSwiftIRRuntimeDynamic.so in the SDK.\n'
})
def _handle_swift_config(self):
"""Handle %swift_config to display configuration."""