-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityBasic.pb
More file actions
4935 lines (3910 loc) · 163 KB
/
Copy pathUnityBasic.pb
File metadata and controls
4935 lines (3910 loc) · 163 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
EnableExplicit
IncludePath "GoScintilla/"
XIncludeFile "GoScintilla.pbi"
#SOURCE_FILE_EXTENSION = ".ubasic"
#UNITY_SERVER_PORT = 10978
#DOC_SERVER_PORT = 17790
Global.s UnityEditorExecutablePath = "C:\Program Files\Unity\Hub\Editor\2020.3.5f1\Editor\Unity.exe"
Global.s UnityPlayerExecutablePath = "C:\Dropbox\Workspaces\UnityBasic_PB\UnityProject\Builds\UnityBasic64.exe"
Global.s GeneratedProjectPath = "C:\Dropbox\Workspaces\UnityBasic_PB\UnityProject"
Global.s GeneratedDocsPath = "C:\Dropbox\Workspaces\UnityBasic_PB\Docs";;;;TODO: kill this
Global.s DocsTemplatePath = "C:\Dropbox\Workspaces\UnityBasic_PB\Docs"
Global.s SourceProjectPath = "C:\Dropbox\Workspaces\UnityBasic_PB\TestProject"
Global.s LibrariesPath = "C:\Dropbox\Workspaces\UnityBasic_PB\Libs"
Global.s TextFilePath = SourceProjectPath + "\TestFile" + #SOURCE_FILE_EXTENSION
Global.s DocURL = "http://127.0.0.1:" + Str( #DOC_SERVER_PORT )
#SPACE = 32
#NEWLINE = 10
#RETURN = 13
#EQUALS = 61
;==============================================================================
;-== UI Setup.
InitScintilla()
InitNetwork()
ExamineDesktops()
; Create a server for communicating with Unity processes (both editor and player).
Define.i UnityServer = CreateNetworkServer( #PB_Any, #UNITY_SERVER_PORT )
If UnityServer = 0
Debug "Cannot create Unity server!!"
;;;;TODO: error
EndIf
; Create a server for serving content to the embedded web browser (though it can be
; accessed by any other browser just the same).
Define.i DocServer = CreateNetworkServer( #PB_Any, #DOC_SERVER_PORT )
If DocServer = 0
Debug "Cannot create doc server!!"
;;;;TODO: error
EndIf
Define.i WindowWidth = DesktopUnscaledX( DesktopWidth( 0 ) )
Define.i WindowHeight = DesktopUnscaledY( DesktopHeight( 0 ) )
Define.i Window = OpenWindow( #PB_Any, 0, 0, WindowWidth, WindowHeight, "Unity Basic", #PB_Window_BorderLess | #PB_Window_ScreenCentered )
SetWindowTitle( Window, "UnityBasic" )
Global.i StatusBar = CreateStatusBar( #PB_Any, WindowID( Window ) )
AddStatusBarField( WindowWidth * 0.05 )
AddStatusBarField( WindowWidth * 0.70 )
AddStatusBarField( WindowWidth * 0.25 )
Define.i ContentWidth = WindowWidth
Define.i ContentHeight = WindowHeight - StatusBarHeight( StatusBar )
Global.i Scintilla = GOSCI_Create( #PB_Any, 0, 0, ContentWidth / 2, ContentHeight, 0, #GOSCI_AUTOSIZELINENUMBERSMARGIN )
;;;;TODO: use navigation callback or popup blocker to navigate from docs to code (put links in generated doc)
Global.i DocViewer = WebGadget( #PB_Any, ContentWidth / 2, 0, ContentWidth / 2, ContentHeight / 2, DocURL )
Global.i PlayerContainer = ContainerGadget( #PB_Any, ContentWidth / 2, ContentHeight / 2, ContentWidth / 2 , ContentHeight / 2 )
;;;;TODO: layout using splitters instead of fixed proportions
;Global Scintilla.i = ScintillaGadget( #PB_Any, 0, 0, 0, 0, 0 )
;Define.i DocViewer = WebGadget( #PB_Any, 0, 0, 0, 0, "https://unity3d.com" )
;Define.i PlayerContainer = ContainerGadget( #PB_Any, 0, 0, 0, 0 )
;Define.i HorizontalSplitter = SplitterGadget( #PB_Any, 0, 0, 0, 0, DocViewer, PlayerContainer )
;Define.i VerticalSplitter = SplitterGadget( #PB_Any, 0, 0, WindowWidth, WindowHeight, Scintilla, HorizontalSplitter, #PB_Splitter_Vertical )
#WINDOW_SAVE_TIMER = 0
#WINDOW_NETWORK_TIMER = 1
AddWindowTimer( Window, #WINDOW_SAVE_TIMER, 2000 )
AddWindowTimer( Window, #WINDOW_NETWORK_TIMER, 500 )
Global.i TextFile
Global.i TextLength = FileSize( TextFilePath )
If TextLength = -1
TextFile = CreateFile( #PB_Any, TextFilePath, #PB_UTF8 | #PB_File_SharedRead )
TextLength = 0
Else
TextFile = OpenFile( #PB_Any, TextFilePath, #PB_UTF8 | #PB_File_SharedRead )
EndIf
Global *Text = AllocateMemory( TextLength + 1024 )
ReadData( TextFile, *Text, TextLength )
PokeB( *Text + TextLength, 0 )
ScintillaSendMessage( Scintilla, #SCI_SETTEXT, 0, *Text )
ScintillaSendMessage( Scintilla, #SCI_SETREADONLY, 0 )
GOSCI_SetAttribute( Scintilla, #GOSCI_LINENUMBERAUTOSIZEPADDING, 10 )
GOSCI_SetMarginWidth( Scintilla, #GOSCI_MARGINFOLDINGSYMBOLS, 24 )
GOSCI_SetColor( Scintilla, #GOSCI_CARETLINEBACKCOLOR, $B4FFFF )
GOSCI_SetFont( Scintilla, "Consolas", 16 )
GOSCI_SetTabs( Scintilla, 4, 1 )
Enumeration Styles
#StyleKeyword = 1
#StyleComment
#StyleString
#StyleNumber
#StyleFunction
#StyleType
#StyleAnnotation
EndEnumeration
GOSCI_SetStyleFont( Scintilla, #StyleKeyword, "", -1, #PB_Font_Bold )
GOSCI_SetStyleColors( Scintilla, #StyleKeyword, $800000 )
GOSCI_SetStyleFont( Scintilla, #StyleAnnotation, "", -1, #PB_Font_Italic )
GOSCI_SetStyleColors( Scintilla, #StyleAnnotation, $006400 )
GOSCI_SetStyleFont( Scintilla, #StyleComment, "", -1, #PB_Font_Italic )
GOSCI_SetStyleColors( Scintilla, #StyleComment, $006400 )
GOSCI_SetStyleColors( Scintilla, #StyleString, #Gray )
GOSCI_SetStyleColors( Scintilla, #StyleFunction, #Blue )
GOSCI_AddDelimiter( Scintilla, "//", "", #GOSCI_DELIMITTOENDOFLINE, #StyleComment )
GOSCI_AddDelimiter( Scintilla, "/*", "*/", #GOSCI_DELIMITTOENDOFLINE, #StyleComment )
GOSCI_AddDelimiter( Scintilla, ~"\"", ~"\"", #GOSCI_DELIMITBETWEEN, #StyleString )
GOSCI_AddKeywords( Scintilla, "TYPE METHOD FIELD OBJECT PROGRAM BEGIN END RETURN ABSTRACT IMMUTABLE MUTABLE IF LOOP", #StyleKeyword )
GOSCI_AddKeywords( Scintilla, "|DESCRIPTION |DETAILS |COMPANY |PRODUCT |CATEGORY |ICALL |PRAGMA", #StyleAnnotation )
GOSCI_SetLexerOption( Scintilla, #GOSCI_LEXEROPTION_SEPARATORSYMBOLS, @"=+-*/%()[],.;" )
Global.i TabWidth = 4
Global.b UseSoftTabs = #True
GOSCI_SetTabs( Scintilla, TabWidth, UseSoftTabs )
ScintillaSendMessage( Scintilla, #SCI_SETINDENTATIONGUIDES, #SC_IV_REAL )
SetActiveGadget( Scintilla )
;==============================================================================
;-== Networking And child processes.
#MAX_MESSAGE_LENGTH = ( 32 * 1024 )
Enumeration Status
#WaitingForEditorToConnect
#WaitingForEditorToBuildPlayer
#WaitingForEditorToBuildAssetBundles
#WaitingForPlayerToConnect
#ReadyState
#BadState ; States we can't yet recover from.
EndEnumeration
Structure UnityProjectSettings
ProductName.s
CompanyName.s
EndStructure
Global.i UnityEditor = RunProgram( UnityEditorExecutablePath, ~"-batchmode -projectPath \"" + GeneratedProjectPath + ~"\" -executeMethod EditorTooling.Run", "", #PB_Program_Open | #PB_Program_Read )
Global.i UnityPlayer
Global.i UnityEditorClient
Global.i UnityPlayerClient
Global.i UnityStatus = #WaitingForEditorToConnect
Global *UnityNetworkBuffer = AllocateMemory( #MAX_MESSAGE_LENGTH )
Global *UnityNetworkBufferPos
Global.i UnityBatchSendClient
Global.UnityProjectSettings UnityProjectSettings
Procedure.s ReceiveString( Client.i )
Define.i ReadResult = ReceiveNetworkData( EventClient(), *UnityNetworkBuffer, #MAX_MESSAGE_LENGTH )
If ReadResult <= 0
Debug "Read failure!!"
ProcedureReturn ""
EndIf
Define.s Text = PeekS( *UnityNetworkBuffer, ReadResult, #PB_UTF8 | #PB_ByteLength )
ProcedureReturn Text
EndProcedure
; Sends some text to a Unity subprocess.
Procedure SendString( Client.i, String.s )
Define.i Length = StringByteLength( String, #PB_UTF8 )
Define *Buffer = AllocateMemory( Length + 1 )
PokeS( *Buffer, String, Length, #PB_UTF8 )
SendNetworkData( Client, *Buffer, Length + 1 )
FreeMemory( *Buffer )
EndProcedure
;;;;REVIEW: seems like we may not even need this and PB is doing this under the hood for us
Procedure StartBatchSend( Client.i )
*UnityNetworkBufferPos = *UnityNetworkBuffer
UnityBatchSendClient = Client
EndProcedure
Procedure FlushBatch()
Define.i Length = *UnityNetworkBufferPos - *UnityNetworkBuffer
If Length > 0
SendNetworkData( UnityBatchSendClient, *UnityNetworkBuffer, Length )
EndIf
*UnityNetworkBufferPos = *UnityNetworkBuffer
EndProcedure
Procedure BatchSendString( String.s )
Define.i Length = StringByteLength( String, #PB_UTF8 )
Define.i Available = *UnityNetworkBufferPos - *UnityNetworkBuffer
If Available < Length + 1 Or Available + Length + 1 > #MAX_MESSAGE_LENGTH
FlushBatch()
EndIf
PokeS( *UnityNetworkBufferPos, String, Length, #PB_UTF8 )
*UnityNetworkBufferPos + Length + 1
EndProcedure
Procedure FinishBatchSend()
FlushBatch()
UnityBatchSendClient = 0
EndProcedure
;==============================================================================
;-== Utilities.
Procedure.i SplitString( Array Split.s( 1 ), String.s, Delimiter.s )
Define.i DelimiterLen = Len( Delimiter )
Define.i StringLen = Len( String )
Define.i Count = CountString( String, Delimiter )
If StringLen > DelimiterLen And FindString( String, Delimiter, StringLen + 1 - DelimiterLen ) = 0
Count + 1
EndIf
ReDim Split( Count )
Define.i Index
Define.i Position = 1
For Index = 0 To Count - 1
Define.i EndPos = FindString( String, Delimiter, Position )
If EndPos = 0
EndPos = Len( String ) + 1
EndIf
Define.s Fragment = Mid( String, Position, EndPos - Position )
Split( Index ) = Fragment
Position = EndPos + DelimiterLen
Next
ProcedureReturn Count
EndProcedure
Structure StringBuilder
*Buffer
Capacity.i
Length.i
EndStructure
Procedure.i AppendString( *Builder.StringBuilder, String.s )
Define.i ByteLength = StringByteLength( String, #PB_UTF8 )
If *Builder\Length + ByteLength > *Builder\Capacity
*Builder\Capacity + ByteLength + 1024
*Builder\Buffer = ReAllocateMemory( *Builder\Buffer, *Builder\Capacity )
EndIf
Define *Ptr = *Builder\Buffer + *Builder\Length
PokeS( *Ptr, String, Len( String ), #PB_UTF8 | #PB_String_NoZero )
*Builder\Length + ByteLength
ProcedureReturn *Ptr
EndProcedure
Procedure FreeStringBuilder( *Builder.StringBuilder )
If *Builder\Buffer <> #Null
FreeMemory( *Builder\Buffer )
EndIf
*Builder\Buffer = #Null
*Builder\Length = 0
*Builder\Capacity = 0
EndProcedure
Procedure ResetStringBuilder( *Builder.StringBuilder )
*Builder\Length = 0
EndProcedure
Procedure.s GetString( *Builder.StringBuilder, FreeBuilder.b = #True )
Define.s String
If *Builder\Length <> 0
String = PeekS( *Builder\Buffer, *Builder\Length, #PB_UTF8 | #PB_ByteLength )
Else
String = ""
EndIf
If FreeBuilder
FreeStringBuilder( *Builder )
EndIf
ProcedureReturn String
EndProcedure
;==============================================================================
; HTTP.
Enumeration HTTPMethod
#HTTPGet
#HTTPPost
EndEnumeration
Structure HTTPRequest
Method.i
Path.s
Map Headers.s()
EndStructure
Structure HTTPResponse
StatusCode.i
Body.s
Map Headers.s()
EndStructure
Procedure.b ParseHTTPRequest( Text.s, *Request.HTTPRequest )
ResetStructure( *Request, HTTPRequest )
Dim Lines.s( 0 )
SplitString( Lines(), Text, ~"\n" )
If ArraySize( Lines() ) < 1
ProcedureReturn #False
EndIf
Dim Fragments.s( 0 )
If SplitString( Fragments(), Lines( 0 ), " " ) <> 3
ProcedureReturn #False
EndIf
Select Fragments( 0 )
Case "GET"
*Request\Method = #HTTPGet
Case "POST"
*Request\Method = #HTTPPost
Default
*Request\Method = -1
EndSelect
*Request\Path = Fragments( 1 )
ProcedureReturn #True
EndProcedure
Procedure.s HTTPStatusCodeToString( StatusCode.i )
Select StatusCode
Case 200
ProcedureReturn "OK"
Default
ProcedureReturn "Hmpf..."
EndSelect
EndProcedure
Procedure.s FormatHTTPResponse( *Response.HTTPResponse )
Define.s Status = "HTTP/1.1 " + Str( *Response\StatusCode ) + " " + HTTPStatusCodeToString( *Response\StatusCode ) + ~"\n"
Define.s Headers = "Content-Length: " + Len( *Response\Body ) + ~"\n"
ForEach *Response\Headers()
Define.s Value = *Response\Headers()
Headers + MapKey( *Response\Headers() ) + ": " + Value + ~"\n"
Next
ProcedureReturn Status + Headers + ~"\n" + *Response\Body
EndProcedure
ProcedureUnit CanParseSimpleHTTPRequest()
Define.s Text = ~"GET / HTTP/1.1\n" +
~"Host: developer.mozilla.org\n" +
~"Accept-Language: fr"
Define.HTTPRequest Request
Assert( ParseHTTPRequest( Text, @Request ) = #True )
Assert( Request\Method = #HTTPGet )
Assert( Request\Path = "/" )
;;;;TODO: headers
EndProcedureUnit
ProcedureUnit CanFormatSimpleHTTPResponse()
Define.HTTPResponse Response
Response\StatusCode = 200
AddMapElement( Response\Headers(), "Content-Type" )
Response\Headers() = "text/html"
Response\Body = "Great!"
;;;;TODO: headers
Define.s Expected = ~"HTTP/1.1 200 OK\n" +
~"Content-Length: 6\n" +
~"Content-Type: text/html\n" +
~"\n" +
~"Great!"
Assert( FormatHTTPResponse( @Response ) = Expected )
EndProcedureUnit
;==============================================================================
;-== Abstract syntax.
;;;;TODO: figure out how to deal with separate files feeding into inputs
Structure TextRegion
LeftPos.i
RightPos.i
EndStructure
;;;;REVIEW: allow specifying annotations that only relate to a certain build platform?
Enumeration AnnotationKind
;;;;REVIEW: rename "DESCRIPTION" to "SUMMARY"??
; Doc annotations.
#DescriptionAnnotation
#DetailsAnnotation
#ExampleAnnotation
#CategoryAnnotation
#ReturnsAnnotation
#ArgumentAnnotation
#TypeArgumentAnnotation
; Test annotations.
#TestAnnotation
; Asset annotations.
#AssetAnnotation
; Program annotations.
#CompanyAnnotation
#ProductAnnotation
#AssetServerAnnotation
; Misc annotations.
#IcallAnnotation
#PragmaAnnotation
EndEnumeration
; Annotations are free-form text blobs that can be attached to definitions.
; They are used as instructions for the tooling.
Structure Annotation
AnnotationKind.i
AnnotationText.s
NextAnnotation.i
EndStructure
Enumeration ClauseKind
#PreconditionClause ; 'requires'
#PostconditionClause ; 'ensures'
#InvariantClause
#WhereClause
EndEnumeration
; Clauses are optional forms that can be tagged onto definitions.
; They are used for things such as pre- and postconditions.
Structure Clause
Expression.i
NextClause.i
EndStructure
#INVALID_TYPE_ID = 0
; During parsing, we assign negative type IDs as stand-ins for types of literals.
; During compilation, these are replaced with actual type IDs.
Enumeration LiteralType
#IntegerLiteralType = -1
#FloatLiteralType = -2
#StringLiteralType = -3
#NothingLiteralType = -4 ; Empty tuple expression '()'. Not translated to 'Nothing' as that would be affected by name lookup rules.
EndEnumeration
Enumeration Operator
#LiteralExpression = 1
#NameExpression
#AndExpression
#OrExpression
#NotExpression
#BitwiseAndExpression
#BitwiseOrExpression
#ApplyExpression ; For types, this instantiates the given named type.
#TupleExpression
#ArrowExpression ; A -> B (type context: function type, value context: anonymous function)
EndEnumeration
Enumeration ExpressionContext
#ValueContext = 1
#TypeContext
EndEnumeration
; Type and value expressions use the same data format.
; All expressions are either unary or binary.
Structure Expression
Operator.b
Context.b
Type.i
Region.TextRegion
StructureUnion
FirstOperandI.i
FirstOperandD.d
EndStructureUnion
SecondOperandI.i
NextExpression.i
EndStructure
Enumeration StatementKind
#ExpressionStatement = 1
#ReturnStatement
#YieldStatement
#LoopStatement
#BreakStatement
#ContinueStatement
#IfStatement
#ElseIfStatement
#ElseStatement
#SwitchStatement
#DefinitionStatement
EndEnumeration
Structure Statement
StatementKind.i
ReferencedIndex.i ; Depends on the kind of statement which array this refers to.
InnerScope.i
NextStatement.i
EndStructure
Enumeration DefinitionKind
#TypeDefinition = 1
#MethodDefinition
#FieldDefinition
#FeatureDefinition
#ModuleDefinition
#LibraryDefinition
#ProgramDefinition
EndEnumeration
EnumerationBinary DefinitionFlags
#IsImport
#IsAbstract
#IsBefore
#IsAfter
#IsAround
#IsImmutable
#IsMutable
#IsSingleton ; 'object' in code
#IsExtend
#IsReplace
#IsIterator
#IsAlias ; for '=' type definitions.
#IsPrivate
EndEnumeration
Structure Parameter
Name.i
TypeExpression.i
DefaultExpression.i ; -1 if none.
NextParameter.i
EndStructure
Structure Definition
Name.i
Scope.i
DefinitionKind.i
Flags.i
TypeExpression.i
InnerScope.i
Region.TextRegion
NextDefinition.i
FirstAnnotation.i ; -1 if none.
FirstClause.i ; -1 if none.
FirstTypeParameter.i ; -1 if none.
FirstValueParameter.i ; -1 if none.
EndStructure
Structure Scope
Parent.i ; -1 is global scope.
Definition.i ; -1 is global scope.
FirstDefinitionOrStatement.i ; Whether definition or statement depends on the type of scope.
EndStructure
Enumeration DiagnosticCode
; Syntax errors.
EndEnumeration
Structure Diagnostic
Code.i
Index.i ; Array is determined automatically from what type of diagnostic it is (based on `Code`).
EndStructure
; Just a bunch of arrays that contain a completely flattened representation of source code.
; No explicit tree structure.
Structure Code
IdentifierCount.i
ScopeCount.i
DefinitionCount.i
StatementCount.i
ExpressionCount.i
AnnotationCount.i
ClauseCount.i
ParameterCount.i
DiagnosticCount.i
ErrorCount.i
WarningCount.i
Map IdentifierTable.i()
Map StringLiterals.i()
Array Identifiers.s( 0 )
Array Scopes.Scope( 1 ) ; First one is always the global scope
Array Definitions.Definition( 0 )
Array Statements.Statement( 0 )
Array Expressions.Expression( 0 )
Array Annotations.Annotation( 0 )
Array Clauses.Clause( 0 )
Array Parameters.Parameter( 0 )
Array Diagnostics.Diagnostic( 0 )
EndStructure
Global Code.Code
Procedure ResetCode()
If Scintilla <> 0
ScintillaSendMessage( Scintilla, #SCI_ANNOTATIONCLEARALL )
EndIf
ResetStructure( @Code, Code )
Code\ScopeCount = 1
Code\Scopes( 1 )\Parent = -1
Code\Scopes( 1 )\Definition = -1
EndProcedure
Procedure.s FormatDiagnostic( Index.i )
EndProcedure
Procedure Diagnose( DiagnosticCode.i, Index.i )
Define.i DiagnosticIndex = Code\DiagnosticCount
If ArraySize( Code\Diagnostics() ) = DiagnosticIndex
ReDim Code\Diagnostics( DiagnosticIndex + 32 )
EndIf
Code\DiagnosticCount + 1
Define.Diagnostic *Diagnostic = @Code\Diagnostics( DiagnosticIndex )
*Diagnostic\Code = DiagnosticCode
*Diagnostic\Index = Index
Debug FormatDiagnostic( DiagnosticIndex )
EndProcedure
Enumeration NamingConvention
#GnuCase ; foo_bar
#JavaCase ; fooBar
#PascalCase ; FooBar
EndEnumeration
Global.i DefaultNamingConvention = #PascalCase
Procedure.s FormatIdentifier( Identifier.s, NamingConvention.i = -1 )
If NamingConvention = -1
NamingConvention = DefaultNamingConvention
EndIf
If NamingConvention = #GnuCase
ProcedureReturn Identifier
EndIf
Dim Parts.s( 0 )
SplitString( Parts(), Identifier, "_" )
Define.i NumParts = ArraySize( Parts() )
Define.StringBuilder Builder
Define.i Index
For Index = 0 To NumParts - 1
Define *Ptr = AppendString( @Builder, Parts( Index ) )
; Uppercase first letter.
If Index <> 0 Or NamingConvention <> #JavaCase
PokeB( *Ptr, PeekB( *Ptr ) - ( 97 - 65 ) )
EndIf
Next
Define.s Result = GetString( @Builder )
ProcedureReturn Result
EndProcedure
ProcedureUnit CanFormatIdentifier()
Assert( FormatIdentifier( "foo_bar", #GnuCase ) = "foo_bar" )
Assert( FormatIdentifier( "foo_bar", #JavaCase ) = "fooBar" )
Assert( FormatIdentifier( "foo_bar", #PascalCase ) = "FooBar" )
EndProcedureUnit
Procedure.s ExpressionKindToString( ExpressionKind.i )
Select ExpressionKind
Case #ApplyExpression
ProcedureReturn "Apply"
Case #TupleExpression
ProcedureReturn "Tuple"
Case #LiteralExpression
ProcedureReturn "Literal"
Case #NameExpression
ProcedureReturn "Name"
Case #AndExpression
ProcedureReturn "And"
Case #OrExpression
ProcedureReturn "Or"
Case #NotExpression
ProcedureReturn "Not"
Case #ArrowExpression
ProcedureReturn "Arrow"
Default
ProcedureReturn "<Unknown>"
EndSelect
EndProcedure
Procedure.s DefinitionKindToString( DefinitionKind.i )
Select DefinitionKind
Case #TypeDefinition
ProcedureReturn "Type"
Case #MethodDefinition
ProcedureReturn "Method"
Case #ProgramDefinition
ProcedureReturn "Program"
Default
ProcedureReturn "???"
EndSelect
EndProcedure
Procedure.i FindAnnotation( *Definition.Definition, AnnotationKind.i )
Define.i AnnotationIndex = *Definition\FirstAnnotation
While AnnotationIndex <> -1
If Code\Annotations( AnnotationIndex )\AnnotationKind = AnnotationKind
ProcedureReturn AnnotationIndex
EndIf
AnnotationIndex = Code\Annotations( AnnotationIndex )\NextAnnotation
Wend
ProcedureReturn -1
EndProcedure
Procedure HasAnnotation( *Definition.Definition, AnnotationKind.i )
ProcedureReturn Bool( FindAnnotation( *Definition, AnnotationKind ) <> -1 )
EndProcedure
;==============================================================================
;-== Parsing.
;;;;TODO: put this on a thread
Structure ParserLocationState
*Position
LastRegion.TextRegion
CurrentLine.i
CurrentColumn.i
EndStructure
Structure Parser Extends ParserLocationState
*EndPosition
*StartPosition
CurrentScope.i
CurrentDefinitionInScope.i
CurrentStatement.i
CurrentExpressionContext.i
FileName.s
NameBufferSize.l
NameBuffer.s
StringBufferSize.l
StringBuffer.s
EndStructure
Macro SaveParserLocation( Parser, LocationVariable )
Define.ParserLocationState LocationVariable
LocationVariable\Position = Parser\Position
LocationVariable\LastRegion = Parser\LastRegion
LocationVariable\CurrentLine = Parser\CurrentLine
LocationVariable\CurrentColumn = Parser\CurrentColumn
EndMacro
Macro RestoreParserLocation( Parser, LocationVariable )
Parser\Position = LocationVariable\Position
Parser\LastRegion = LocationVariable\LastRegion
Parser\CurrentLine = LocationVariable\CurrentLine
Parser\CurrentColumn = LocationVariable\CurrentColumn
EndMacro
Macro PushExpressionContext( Parser, Context )
Define.i PreviousExpressionContext = Parser\CurrentExpressionContext
Parser\CurrentExpressionContext = Context
EndMacro
Macro PopExpressionContext( Parser )
Parser\CurrentExpressionContext = PreviousExpressionContext
EndMacro
Macro PushScope( Parser )
Define.i PreviousScope = Parser\CurrentScope
Define.i PreviousDefinitionInScope = Parser\CurrentDefinitionInScope
Define.i PreviousStatementInScope = Parser\CurrentStatement
Define.i CurrentScope = Code\ScopeCount
If ArraySize( Code\Scopes() ) = CurrentScope
ReDim Code\Scopes( CurrentScope + 256 )
EndIf
Code\ScopeCount + 1
Code\Scopes( CurrentScope )\FirstDefinitionOrStatement = -1
Code\Scopes( CurrentScope )\Parent = PreviousScope
Parser\CurrentScope = CurrentScope
Parser\CurrentDefinitionInScope = -1
Parser\CurrentStatement = -1
EndMacro
Macro PopScope( Parser )
Parser\CurrentScope = PreviousScope
Parser\CurrentDefinitionInScope = PreviousDefinionInScope
Parser\CurrentStatement = PreviousStatementInScope
CurrentScope = PreviousScope
EndMacro
Macro MakeExpressionOpI( IndexVariable, Op, Tp, Operand, StartPos )
Define.i IndexVariable = Code\ExpressionCount
If ArraySize( Code\Expressions() ) = IndexVariable
ReDim Code\Expressions( IndexVariable + 1024 )
EndIf
Code\ExpressionCount + 1
Define.Expression *Expression = @Code\Expressions( IndexVariable )
*Expression\Operator = Op
*Expression\Context = *Parser\CurrentExpressionContext
*Expression\Type = Tp
*Expression\FirstOperandI = Operand
*Expression\Region\LeftPos = StartPos
*Expression\Region\RightPos = *Parser\Position - *Parser\StartPosition
*Expression\NextExpression = -1
EndMacro
Macro MakeExpressionOp2I( IndexVariable, Op, Tp, Operand1, Operand2, StartPos )
Define.i IndexVariable = Code\ExpressionCount
If ArraySize( Code\Expressions() ) = IndexVariable
ReDim Code\Expressions( IndexVariable + 1024 )
EndIf
Code\ExpressionCount + 1
Define.Expression *Expression = @Code\Expressions( IndexVariable )
*Expression\Operator = Op
*Expression\Context = *Parser\CurrentExpressionContext
*Expression\Type = Tp
*Expression\FirstOperandI = Operand1
*Expression\SecondOperandI = Operand2
*Expression\Region\LeftPos = StartPos
*Expression\Region\RightPos = *Parser\Position - *Parser\StartPosition
*Expression\NextExpression = -1
EndMacro
Macro MakeStatement( IndexVariable, Kind, Reference, Scope = -1 )
Define.i IndexVariable = Code\StatementCount
If ArraySize( Code\Statements() ) = IndexVariable
ReDim Code\Statements( IndexVariable + 1024 )
EndIf
Define.Statement *Statement = @Code\Statements( IndexVariable )
Code\StatementCount + 1
*Statement\StatementKind = Kind
*Statement\ReferencedIndex = Reference
*Statement\InnerScope = Scope
*Statement\NextStatement = -1
If *Parser\CurrentStatement <> -1
Code\Statements( *Parser\CurrentStatement )\NextStatement = IndexVariable
EndIf
*Parser\CurrentStatement = IndexVariable
EndMacro
Procedure.c ToLower( Character.c )
;;;;FIXME: Not Unicode...
If Character >= 65 And Character <= 90
ProcedureReturn 97 + ( Character - 65 )
EndIf
ProcedureReturn Character
EndProcedure
Procedure.b IsUpper( Character.c )
;;;;FIXME: Not Unicode...
If Character >= 65 And Character <= 90
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
Procedure.i IsWhitespace( Character.c )
Select Character
Case #TAB, #SPACE, #NEWLINE, #RETURN
ProcedureReturn #True
EndSelect
ProcedureReturn #False
EndProcedure
Procedure.i IsAlpha( Character.c )
;;;;FIXME: Not Unicode...
If Character >= 65 And Character <= 90
ProcedureReturn #True
EndIf
If Character >= 97 And Character <= 122
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
Procedure.i IsDigit( Character.c )
;;;;FIXME: Not Unicode...
If Character >= 48 And Character <= 57
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
Procedure.i IsAlphanumeric( Character.c )
If IsAlpha( Character ) Or IsDigit( Character )
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
; Skips over whitespace characters and comments.
Procedure SkipWhitespace( *Parser.Parser, AllowNewline.b = #True )
Define.i CommentNestingDepth = 0
While *Parser\Position < *Parser\EndPosition
Define.b Char = PeekB( *Parser\Position )
; Comments.
; We don't allow comments in 'Not AllowNewline' sectiosn
If AllowNewline And Char = '/' And *Parser\EndPosition - *Position >= 2
Define.b NextChar = PeekB( *Parser\Position + 1 )
If NextChar = '/' And CommentNestingDepth = 0
*Parser\Position + 2
*Parser\CurrentColumn + 2
While *Parser\Position < *Parser\EndPosition
Char = PeekB( *Parser\Position )
If Char = #NEWLINE
Break
EndIf
*Parser\Position + 1
*Parser\CurrentColumn + 1
Wend
ElseIf NextChar = '*'
*Parser\Position + 2
*Parser\CurrentColumn + 2
CommentNestingDepth + 1
If *Parser\Position < *Parser\EndPosition
Char = PeekB( *Parser\Position )
Else
Break
EndIf
EndIf
ElseIf CommentNestingDepth > 0 And Char = '*' And *Parser\EndPosition - *Position >= 2
Define.b NextChar = PeekB( *Parser\Position + 1 )
If NextChar = '/'
CommentNestingDepth - 1
*Parser\Position + 2
*Parser\CurrentColumn + 2
If *Parser\Position < *Parser\EndPosition
Char = PeekB( *Parser\Position )
Else
Break
EndIf
EndIf
EndIf
If Not AllowNewline And Char = #NEWLINE
Break
EndIf
If Not IsWhitespace( Char ) And CommentNestingDepth = 0
Break
EndIf