-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseaplus_parse_transform.erl
More file actions
1244 lines (848 loc) · 42.7 KB
/
Copy pathseaplus_parse_transform.erl
File metadata and controls
1244 lines (848 loc) · 42.7 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
% Copyright (C) 2019-2026 Olivier Boudeville
%
% This file is part of the Ceylan-Seaplus library.
%
% This library is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License or
% the GNU General Public License, as they are published by the Free Software
% Foundation, either version 3 of these Licenses, or (at your option)
% any later version.
% You can also redistribute it and/or modify it under the terms of the
% Mozilla Public License, version 1.1 or later.
%
% This library is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License and the GNU General Public License
% for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License, of the GNU General Public License and of the Mozilla Public License
% along with this library.
% If not, see <http://www.gnu.org/licenses/> and
% <http://www.mozilla.org/MPL/>.
%
% Author: Olivier Boudeville [olivier (dot) boudeville (at) esperide (dot) com]
% Creation date: Tuesday, January 29, 2019.
-module(seaplus_parse_transform).
-moduledoc """
Overall *parse transform for the Seaplus layer*, in charge of streamlining the
integration of any C-based service.
Meant, for a `Foobar` service, to operate on a `foobar.erl` stub, so that:
- a fully-functional `foobar` module becomes available
- a corresponding `foobar_seaplus_api_mapping.h` C header is generated in order
to ease the development of the corresponding C-side driver
""".
% Implementation notes:
% Calls in turn the Myriad parse transform, before and after the Seaplus-level
% operations have been completed (respectively to obtain a module_info as input
% for Seaplus, and to transform adequately, as standard Erlang code, any
% Seaplus-injected code that would rely on Myriad conventions).
%
% One will get: 'undefined parse transform 'seaplus_parse_transform'' as soon as
% a compiled module called by the parse transform (e.g. text_utils.beam) will
% not be found (hence even if the transform itself is available) or a
% non-exported (or even not existing) function is called
% (e.g. text_utils:format/1).
% Regarding the Seaplus parse transform.
%
% This parse transform will largely transform and enrich a module stub
% corresponding to a service.
%
% However, multiple modules exist in the Seaplus layer, some of which must
% undergo such a transformation, some others not (e.g. they are just helper
% modules).
%
% To discriminate between these two sets, we do not rely on the module name, as
% we do not want to constrain the name of the bridging module (e.g. 'foobar' is
% fine, we do not want to make a longer form such as 'foobar_service'
% mandatory).
%
% So the trigger of the actual Seaplus transformations will be the definition of
% a specific function, activate_seaplus/1, a default implementation of which
% being defined in seaplus.hrl.
%
% As a result, including that header will imply that the module at hand is a
% Seaplus stub.
% Possible improvement: generate and store in SERVICE.beam a reverse table in
% order to be able to translate a function driver ID (e.g. specified as '#define
% GET_SIGNAL_QUALITY_0_ID 9' in SERVICE_seaplus_api_mapping.h) into the name and
% arity of that function (e.g. get_signal_quality/0); useful notably to better
% report errors.
-export([ run_standalone/1, run_standalone/2,
parse_transform/2, apply_seaplus_transform/3 ]).
% For function_info:
-include_lib("myriad/include/ast_info.hrl").
% For ast_transforms undefined record:
-include_lib("myriad/include/ast_transform.hrl").
% Local type:
-type dict_key() :: atom().
% Local type shorthands:
-type ast() :: ast_base:ast().
-type module_info() :: ast_info:module_info().
-type function_info() :: ast_info:function_info().
-type ast_transforms() :: ast_transform:ast_transforms().
-type preprocessor_option() :: ast_utils:preprocessor_option().
-type parse_transform_options() :: meta_utils:parse_transform_options().
-type file_name() :: file_utils:file_name().
-type directory_name() :: file_utils:directory_name().
-type directory_path() :: file_utils:directory_path().
-type function_driver_id() :: seaplus:function_driver_id().
-ifdef(enable_seaplus_traces).
-define( display_trace( S ), trace_bridge:debug( "[Seaplus] " ++ S ) ).
-define( display_trace( S, F ),
ast_utils:debug_fmt( "[Seaplus] " ++ S, F ) ).
-else. % enable_seaplus_traces
% To avoid variables being reported as unused depending on the mode:
-define( display_trace( S ),
basic_utils:ignore_unused( { seaplus_trace_disabled, S } ) ).
-define( display_trace( S, F ),
basic_utils:ignore_unused({ seaplus_trace_disabled, S, F } ) ).
-endif. % enable_seaplus_traces
% Implementation notes:
% For log output, even if io:format/{1,2} and ast_utils:display_*/* work, we
% recommend using trace_bridge:*/*.
-doc """
Runs the Seaplus parse transform defined here in a standalone way (that is
without being triggered by the usual, integrated compilation process), with no
specific preprocessor option.
This allows to benefit from all compilation error and warning messages, whereas
they are seldom available from a code directly run as a parse transform
(e.g. `undefined parse transform 'foobar'` as soon as a function or a module is
not found).
""".
-spec run_standalone( file_name() ) -> { ast(), module_info() }.
run_standalone( FileToTransform ) ->
run_standalone( FileToTransform, _PreprocessorOptions=[] ).
-doc """
Runs the Seaplus parse transform defined here in a standalone way (that is
without being triggered by the usual, integrated compilation process), with
specified preprocessor options.
This allows to benefit from all compilation error and warning messages, whereas
they are seldom available from a code directly run as a parse transform
(e.g. `undefined parse transform 'foobar'` as soon as a function or a module is
not found).
""".
-spec run_standalone( file_name(), [ preprocessor_option() ] ) ->
{ ast(), module_info() }.
run_standalone( FileToTransform, PreprocessorOptions ) ->
InputAST = ast_utils:erl_to_ast( FileToTransform, PreprocessorOptions ),
% Necessary to fetch resources:
SeaplusRootDir = get_seaplus_root( PreprocessorOptions ),
% Returns {SeaplusAST, ModuleInfo}:
apply_seaplus_transform( InputAST, SeaplusRootDir, _Options=[] ).
-doc """
The parse transform itself, generating notably (Myriad-based) Abstract Format
code, before being itself converted in turn into an Erlang-compliant Abstract
Format code.
""".
-spec parse_transform( ast(), meta_utils:parse_transform_options() ) -> ast().
parse_transform( InputAST, Options ) ->
%trace_bridge:debug_fmt( "Seaplus input AST:~n~p~n", [ InputAST ] ),
%trace_bridge:debug_fmt( "Seaplus options:~n~p~n", [ Options ] ),
% Necessary to fetch resources:
SeaplusRootDir = get_seaplus_root( Options ),
%ast_utils:write_ast_to_file( InputAST, "Seaplus-input-AST.txt" ),
% In the context of this direct parse transform, the module_info is of no
% use afterwards and thus can be dropped:
%
{ SeaplusAST, _ModuleInfo } =
apply_seaplus_transform( InputAST, Options, SeaplusRootDir ),
%trace_bridge:debug_fmt( "Seaplus output AST:~n~p~n", [ SeaplusAST ] ),
%ast_utils:write_ast_to_file( SeaplusAST, "Seaplus-output-AST.txt" ),
SeaplusAST.
-doc """
Returns the root directory of Seaplus, as specified in the build defines.
""".
get_seaplus_root( Options ) ->
case [ RootDir || { d, 'seaplus_root', RootDir } <- Options ] of
[ RootDirectory ] ->
% As a _checkout symlink might be used:
case file_utils:is_existing_directory_or_link( RootDirectory ) of
true ->
%trace_bridge:debug_fmt( "Seaplus directory is '~ts'.",
% [ RootDirectory ] ),
TestFile = file_utils:join(
[ RootDirectory, "include", "seaplus.h" ] ),
case file_utils:is_existing_file( TestFile ) of
true ->
RootDirectory;
false ->
trace_bridge:error_fmt( "The Seaplus root directory"
" specified in the build options, '~ts', does "
"not seem to be a legit one (no '~ts' file "
"found, while being in '~ts').",
[ RootDirectory, TestFile,
file_utils:get_current_directory() ] ),
throw( { invalid_seaplus_root_directory,
RootDirectory } )
end;
false ->
trace_bridge:error_fmt( "The Seaplus root directory '~ts', "
"as specified in the build options, does not exist "
"(while being in '~ts').",
[ RootDirectory, file_utils:get_current_directory() ] ),
throw( { seaplus_root_directory_not_found, RootDirectory } )
end;
[] ->
trace_bridge:error_fmt( "No Seaplus root directory set in build "
"settings (requiring '-Dseaplus_root=SOME_DIR').~n"
"Build options were: ~p; current directory being '~ts'.",
[ Options, file_utils:get_current_directory() ] ),
throw( seaplus_root_directory_not_set );
Others ->
trace_bridge:error_fmt( "Multiple Seaplus directories set: ~p.",
[ Others ] ),
throw( { multiple_seaplus_root_directories, Others } )
end.
-doc "Transforms the specified AST for Seaplus.".
-spec apply_seaplus_transform( ast(), parse_transform_options(),
directory_path() ) -> { ast(), module_info() }.
apply_seaplus_transform( InputAST, Options, SeaplusRootDir ) ->
%trace_bridge:debug_fmt( " (applying parse transform '~p')", [ ?MODULE ] ),
%trace_bridge:debug_fmt( "~n## INPUT ###################################" ),
%trace_bridge:debug_fmt( "Seaplus input AST:~n~p~n~n", [ InputAST ] ),
%ast_utils:display_debug( "Seaplus options:~n~p~n", [ Options ] ),
%ast_utils:write_ast_to_file( InputAST, "Seaplus-input-AST.txt" ),
% This allows to compare input and output ASTs more easily:
%ast_utils:write_ast_to_file( lists:sort( InputAST ),
% "Seaplus-input-AST-sorted.txt" ),
% First preprocesses the AST based on the Myriad parse transform, in order
% to benefit from its corresponding module_info record:
% (however no Myriad-level transformation performed yet)
%
BaseModuleInfo = ast_info:extract_module_info_from_ast( InputAST ),
WithOptsModuleInfo = ast_info:interpret_options( Options, BaseModuleInfo ),
?display_trace( "Module information extracted." ),
%ast_utils:display_debug( "Module information, directly as obtained "
% "from Myriad (untransformed): ~ts",
% [ ast_info:module_info_to_string( WithOptsModuleInfo ) ] ),
% The Seaplus augmentations must be applied only to modules corresponding to
% services to be integrated (not to all modules):
%
ProcessedModuleInfo = case is_integration_module( WithOptsModuleInfo ) of
false ->
% Then Seaplus does nothing specific:
WithOptsModuleInfo;
ShrunkModuleInfo ->
% Then promote this Myriad-level information into a Seaplus one:
% (here is the real Seaplus magic, if any)
%
process_module_info_from( ShrunkModuleInfo, SeaplusRootDir )
end,
% In all cases, Myriad transformation shall happen (e.g. at the very least,
% we want types like void() to be transformed):
%
{ FinalModuleInfo, _MyriadTransforms } =
myriad_parse_transform:transform_module_info( ProcessedModuleInfo ),
%trace_bridge:debug_fmt(
% "Module information after Seaplus: ~ts",
% [ ast_info:module_info_to_string( FinalModuleInfo ) ] ),
?display_trace( "Module information processed, "
"recomposing corresponding AST." ),
OutputAST = ast_info:recompose_ast_from_module_info(
FinalModuleInfo ),
%trace_bridge:debug_fmt( "Seaplus output AST:~n~p", [ OutputAST ] ),
%OutputASTFilename = text_utils:format(
% "Seaplus-output-AST-for-module-~ts.txt",
% [ element( 1, FinalModuleInfo#module_info.module ) ] ),
%
%ast_utils:write_ast_to_file( OutputAST, OutputASTFilename ),
%OutputSortedASTFilename = text_utils:format(
% "Seaplus-sorted-output-AST-for-module-~ts.txt",
% [ element( 1, FinalModuleInfo#module_info.module ) ] ),
%
%ast_utils:write_ast_to_file( lists:sort( OutputAST ),
% OutputSortedASTFilename ),
{ OutputAST, ProcessedModuleInfo }.
-doc """
Determines whether the specified module info corresponds to a
service-integration module, that is a module that Seaplus shall augment based on
the unimplemented specs found.
""".
-spec is_integration_module( module_info() ) -> 'false' | module_info().
is_integration_module( ModuleInfo=#module_info{ functions=FunctionTable } ) ->
MarkerFunId = { activate_seaplus, 1 },
% A module will be a service-integration one iff activate_seaplus/1 has been
% defined (probably automatically, by including seaplus.hrl), in which case
% it will be removed:
%
case table:extract_entry_if_existing( MarkerFunId, FunctionTable ) of
false ->
%trace_bridge:debug(
% "(not detected as a service-integration module)" ),
false;
{ #function_info{ exported=ExportLocs }, ShrunkFunctionTable } ->
%trace_bridge:debug( "(detected as a service-integration module)" ),
% It must also be un-exported:
FunExportTable = ModuleInfo#module_info.function_exports,
ShrunkFunExportTable = ast_info:ensure_function_not_exported(
MarkerFunId, ExportLocs, FunExportTable ),
ModuleInfo#module_info{
function_exports=ShrunkFunExportTable,
functions=ShrunkFunctionTable }
end.
-doc "Applies the actual Seaplus transformations.".
-spec process_module_info_from( module_info(), directory_name() ) ->
module_info().
process_module_info_from( ModuleInfo=#module_info{ module={ ModName, _Loc } },
SeaplusRootDir ) ->
% Should start, stop, etc. be specifically defined by the integration
% module:
%
ControleModuleInfo = handle_control_functions( ModuleInfo ),
% Useful to have a deep look into the target module for which a driver will
% be generated:
%
%trace_bridge:debug_fmt( "Control-augmented module: ~ts",
% [ ast_info:module_info_to_string( ControleModuleInfo ) ] ),
ReadyFunInfos = prepare_api_functions( ControleModuleInfo ),
SelectFunIds = [ { Name, Arity }
|| #function_info{ name=Name, arity=Arity } <- ReadyFunInfos ],
FullModuleInfo = case SelectFunIds of
[] ->
% We nevertheless may want a (empty) header file to be produced:
trace_bridge:debug( "No API function detected." ),
ControleModuleInfo;
_ ->
trace_bridge:debug_fmt( "Selected ~B function(s) for API: ~ts",
[ length( SelectFunIds ), text_utils:strings_to_string(
[ ast_info:function_id_to_string( Id )
|| Id <- SelectFunIds ] ) ] ),
% Generating the header for the driver:
HeaderFilename = generate_driver_header( ModName, SelectFunIds ),
manage_driver_implementation( ModName, SelectFunIds,
HeaderFilename, SeaplusRootDir ),
reinject_fun_infos( ReadyFunInfos, ControleModuleInfo )
end,
% At the very least, we want types like void() to be transformed:
{ MyriadModuleInfo, _MyriadTransforms } =
myriad_parse_transform:transform_module_info( FullModuleInfo ),
MyriadModuleInfo.
-doc "Manages any user-defined control function (e.g. start, stop).".
-spec handle_control_functions( module_info() ) -> module_info().
handle_control_functions( ModuleInfo ) ->
StartModInfo = handle_start_function( ModuleInfo ),
StartLinkModInfo = handle_start_link_function( StartModInfo ),
StopModInfo = handle_stop_function( StartLinkModInfo ),
StopModInfo.
-doc "Ensures that the `start/0` function starts Seaplus as well.".
handle_start_function( ModuleInfo=#module_info{
module={ ModName, _LocForm },
functions=FunctionTable } ) ->
StartFunId = { start, 0 },
Line = 0,
% This call shall be made in all cases:
SeaplusStartCall = { call, Line, { remote, Line, {atom,Line,seaplus},
{atom,Line,start} }, [ {atom,Line,ModName} ] },
%trace_bridge:debug_fmt( "Start call: '~p'.", [ SeaplusStartCall ] ),
case table:extract_entry_if_existing( StartFunId, FunctionTable ) of
% Here, start/0 is (surprisingly) exported, but not defined by the
% user:
%
{ #function_info{ clauses=[] }, ShrunkTable } ->
trace_bridge:debug( "No user-defined start/0 found "
"(yet was exported), generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStartCall ] },
% Auto-exports:
meta_utils:add_function( StartFunId, _Clauses=[ Clause ],
ModuleInfo#module_info{ functions=ShrunkTable } );
% Mostly the same:
false ->
trace_bridge:debug( "No user-defined start/0 found, "
"generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStartCall ] },
% Auto-exports:
meta_utils:add_function( StartFunId, _Clauses=[ Clause ],
ModuleInfo );
% User-defined start/0 available here:
{ FunInfo=#function_info{ clauses=Clauses,
exported=Exports }, ShrunkTable } ->
trace_bridge:debug( "User-defined start/0 found, enriching it." ),
% We just ensure that (all clauses of) this function call first
% seaplus:start(?MODULE), and then continue with the pre-existing
% user code:
%
NewClauses = [ { clause, L, HSeq, GSeq,
[ SeaplusStartCall | Body ] }
|| { clause, L, HSeq, GSeq, Body } <- Clauses ],
% Ensures exported exactly once:
NewExports = case Exports of
[] ->
[ ast_info:get_default_export_function_location() ];
_ ->
Exports
end,
NewFunInfo = FunInfo#function_info{ clauses=NewClauses,
exported=NewExports },
NewFunctionTable =
table:add_entry( StartFunId, NewFunInfo, ShrunkTable ),
ModuleInfo#module_info{ functions=NewFunctionTable }
end.
-doc "Ensures that the `start_link/0` function starts Seaplus as well.".
handle_start_link_function( ModuleInfo=#module_info{
module={ ModName, _LocForm },
functions=FunctionTable } ) ->
StartLinkFunId = { start_link, 0 },
Line = 0,
% This call shall be made in all cases:
SeaplusStartLinkCall = { call, Line, { remote, Line, {atom,Line,seaplus},
{atom,Line,start_link} }, [ {atom,Line,ModName} ] },
%trace_bridge:debug_fmt( "Start link call: '~p'.",
% [ SeaplusStartLinkCall ] ),
case table:extract_entry_if_existing( StartLinkFunId, FunctionTable ) of
% Here, start_link/0 is (surprisingly) exported, but not defined by the
% user:
%
{ #function_info{ clauses=[] }, ShrunkTable } ->
trace_bridge:debug( "No user-defined start_link/0 found "
"(yet was exported), generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStartLinkCall ] },
% Auto-exports:
meta_utils:add_function( StartLinkFunId, _Clauses=[ Clause ],
ModuleInfo#module_info{ functions=ShrunkTable } );
% Mostly the same:
false ->
trace_bridge:debug( "No user-defined start_link/0 found, "
"generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStartLinkCall ] },
% Auto-exports:
meta_utils:add_function( StartLinkFunId, _Clauses=[ Clause ],
ModuleInfo );
% User-defined start_link/0 available here:
{ FunInfo=#function_info{ clauses=Clauses,
exported=Exports }, ShrunkTable } ->
trace_bridge:debug(
"User-defined start_link/0 found, enriching it." ),
% We just ensure that (all clauses of) this function call first
% seaplus:start_link( ?MODULE ), and then continue with the
% pre-existing user code:
%
NewClauses = [ { clause, L, HSeq, GSeq,
[ SeaplusStartLinkCall | Body ] }
|| { clause, L, HSeq, GSeq, Body } <- Clauses ],
% Ensures exported exactly once:
NewExports = case Exports of
[] ->
[ ast_info:get_default_export_function_location() ];
_ ->
Exports
end,
NewFunInfo = FunInfo#function_info{ clauses=NewClauses,
exported=NewExports },
NewFunctionTable =
table:add_entry( StartLinkFunId, NewFunInfo, ShrunkTable ),
ModuleInfo#module_info{ functions=NewFunctionTable }
end.
-doc "Ensures that the `stop/0` function stops Seaplus as well.".
handle_stop_function( ModuleInfo=#module_info{ module={ ModName, _LocForm },
functions=FunctionTable } ) ->
StopFunId = { stop, 0 },
Line = 0,
% This call shall be made in all cases:
SeaplusStopCall = { call, Line, { remote, Line, {atom,Line,seaplus},
{atom,Line,stop} }, [ {atom,Line,ModName} ] },
%trace_bridge:debug_fmt( "Stop call: ~p", [ SeaplusStopCall ] ),
case table:extract_entry_if_existing( StopFunId, FunctionTable ) of
% Here, stop/0 is (surprisingly) exported, but not defined by the
% user:
%
{ #function_info{ clauses=[] }, ShrunkTable } ->
trace_bridge:debug( "No user-defined stop/0 found "
"(yet was exported), generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStopCall ] },
% Auto-exports:
meta_utils:add_function( StopFunId, _Clauses=[ Clause ],
ModuleInfo#module_info{ functions=ShrunkTable } );
% Mostly the same:
false ->
trace_bridge:debug(
"No user-defined stop/0 found, generating it." ),
Clause = { clause, Line, _HeadPattSeq=[], _GuardSeq=[],
[ SeaplusStopCall ] },
% Auto-exports:
meta_utils:add_function( StopFunId, _Clauses=[ Clause ],
ModuleInfo );
% User-defined stop/0 available here:
{ FunInfo=#function_info{ clauses=Clauses,
exported=Exports }, ShrunkTable } ->
trace_bridge:debug( "User-defined stop/0 found, enriching it." ),
% We just ensure that (all clauses of) this function starts with the
% pre-existing user code and then finishes with a call to
% seaplus:stop().
%
NewClauses = [ { clause, L, HSeq, GSeq,
list_utils:append_at_end( SeaplusStopCall, Body ) }
|| { clause, L, HSeq, GSeq, Body } <- Clauses ],
% Ensures exported exactly once:
NewExports = case Exports of
[] ->
[ ast_info:get_default_export_function_location() ];
_ ->
Exports
end,
NewFunInfo = FunInfo#function_info{ clauses=NewClauses,
exported=NewExports },
NewFunctionTable =
table:add_entry( StopFunId, NewFunInfo, ShrunkTable ),
ModuleInfo#module_info{ functions=NewFunctionTable }
end.
-doc "Generates the relevant C header file for the service driver.".
generate_driver_header( ServiceModuleName, FunIds ) ->
HeaderFilename = text_utils:format( "~ts_seaplus_api_mapping.h",
[ ServiceModuleName ] ),
trace_bridge:debug_fmt( "Generating the '~ts' header file, comprising ~B "
"function mappings.", [ HeaderFilename, length( FunIds ) ] ),
% Being a generated file, it can be overwritten with no regret:
HeaderFile = file_utils:open( HeaderFilename, _Opts=[ write, raw ] ),
StringModName = text_utils:atom_to_string( ServiceModuleName ),
IncGuard = text_utils:format( "_~ts_SEAPLUS_API_MAPPING_H_",
[ text_utils:to_uppercase( StringModName ) ] ),
file_utils:write_ustring( HeaderFile, "#ifndef ~ts~n#define ~ts~n~n",
[ IncGuard, IncGuard ] ),
file_utils:write_ustring( HeaderFile,
"/* This header file has been generated by the Seaplus integration~n"
" * bridge for the '~ts' service, on ~ts.~n"
" */~n~n",
[ StringModName, time_utils:get_textual_timestamp() ] ),
file_utils:write_ustring( HeaderFile,
"/* For each of the exposed functions of the API, "
"a Seaplus identifier is~n"
" * generated to ensure that the C code of the driver "
"can stay in sync with~n"
" * the Erlang view on said API, regardless of its "
"changes.~n */~n~n", [] ),
write_mapping( HeaderFile, FunIds, _Count=1 ),
file_utils:write_ustring( HeaderFile, "~n#endif // ~ts~n", [ IncGuard ] ),
file_utils:close( HeaderFile ),
HeaderFilename.
% (helper)
write_mapping( _HeaderFile, _FunIds=[], _Count ) ->
ok;
write_mapping( HeaderFile, _FunIds=[ { FunName, Arity } | T ], Count ) ->
FunSymbol = get_driver_id_for( FunName, Arity ),
file_utils:write_ustring( HeaderFile, "#define ~ts ~B~n",
[ FunSymbol, Count ] ),
write_mapping( HeaderFile, T, Count+1 ).
-doc "Returns the C driver identifier for the specified function.".
get_driver_id_for( FunName, Arity ) ->
FunString = text_utils:to_uppercase( text_utils:atom_to_string( FunName ) ),
text_utils:format( "~ts_~B_ID", [ FunString, Arity ] ).
-doc "Creates an implementation stub for the driver, if no such file exists.".
manage_driver_implementation( ServiceModuleName, FunIds, HeaderFilename,
SeaplusRootDir ) ->
SourceFilename = text_utils:format( "~ts_seaplus_driver.c",
[ ServiceModuleName ] ),
case file_utils:is_existing_file_or_link( SourceFilename ) of
true ->
trace_bridge:info_fmt( "Driver implementation ('~ts') already "
"existing, not generating it.", [ SourceFilename ] );
false ->
trace_bridge:info_fmt( "No driver implementation ('~ts') found, "
"generating it.", [ SourceFilename ] ),
generate_driver_implementation( ServiceModuleName, FunIds,
HeaderFilename, SourceFilename, SeaplusRootDir )
end.
-doc """
Generates the implementation stub for the driver, overwriting it if needed.
""".
generate_driver_implementation( ServiceModuleName, FunIds, HeaderFilename,
SourceFilename, SeaplusRootDir ) ->
TemplateBaseDir = file_utils:join( SeaplusRootDir, "src" ),
DriverHeaderFilename =
file_utils:join( TemplateBaseDir, "seaplus_driver_header.c" ),
file_utils:is_existing_file( DriverHeaderFilename ) orelse
throw( { driver_header_not_found, DriverHeaderFilename } ),
HeaderContent = file_utils:read_whole( DriverHeaderFilename ),
%trace_bridge:debug_fmt( "Read content:~n~ts",
% [ HeaderContent ] ),
HHeaderContent = string:replace( HeaderContent,
"##SEAPLUS_SERVICE_HEADER_FILE##", HeaderFilename, all ),
%trace_bridge:debug_fmt( "New content:~n~ts", [ HHeaderContent ] ),
StringServiceModuleName = text_utils:atom_to_string( ServiceModuleName ),
NHeaderContent = string:replace( HHeaderContent,
"##SEAPLUS_SERVICE_NAME##", StringServiceModuleName, all ),
%trace_bridge:debug_fmt( "Generated driver header:~n~ts",
% [ NHeaderContent ] ),
DriverFooterFilename =
file_utils:join( TemplateBaseDir, "seaplus_driver_footer.c" ),
file_utils:is_existing_file( DriverFooterFilename ) orelse
throw( { driver_footer_not_found, DriverFooterFilename } ),
FooterContent = file_utils:read_whole( DriverFooterFilename ),
SourceFile = file_utils:open( SourceFilename, _Opts=[ write, raw ] ),
file_utils:write_ustring( SourceFile, NHeaderContent ),
write_cases( SourceFile, FunIds ),
file_utils:write_ustring( SourceFile, FooterContent ),
file_utils:close( SourceFile ).
write_cases( _SourceFile, _FunIds=[] ) ->
ok;
write_cases( SourceFile, _FunIds=[ { FunName, Arity } | T ] ) ->
DriverId = get_driver_id_for( FunName, Arity ),
Snippet = text_utils:format(
"\tcase ~ts:~n~n"
"\t\tLOG_DEBUG( \"Executing ~ts/~B.\" ) ;~n"
"\t\tcheck_arity_is( ~B, param_count, ~ts ) ;~n~n"
"\t\t// Add an Erlang term -> C conversion here for each "
"parameter of~n"
"\t\t// interest (refer to seaplus_getters.h for the conversion "
"functions).~n~n"
"\t\t// As an example, supposing that a single input parameter of "
"type 'int'~n\t\t// applies for this ~ts/~B function:~n"
"\t\t// int i = read_int_parameter(read_buf, &index) ;~n~n"
"\t\t// This allows then calling the C counterpart of~n"
"\t\t// the ~ts/~B function, for example:~n"
"\t\t// float f = some_service_function(i) ;~n~n"
"\t\t// Then write the returned result to the Erlang side:~n"
"\t\t// (refer to seaplus_setters.h for the conversion functions)"
"~n"
"\t\t// For example write_double_result(&output_sm_buf, "
"(double) f) ;~n~n"
"\t\t// Do not forget to deallocate any relevant memory!~n"
"\t\t// (refer to foobar_seaplus_driver.c for an example)~n~n"
"\t\tbreak ;~n",
[ DriverId, FunName, Arity, Arity, DriverId, FunName, Arity, FunName,
Arity ] ),
file_utils:write_ustring( SourceFile, "~n~ts~n", [ Snippet ] ),
write_cases( SourceFile, T ).
-doc "Identifies the API functions, processes and sorts them.".
-spec prepare_api_functions( module_info() ) -> [ function_info() ].
prepare_api_functions( ModuleInfo=#module_info{ functions=FunctionTable,
markers=MarkerTable } ) ->
% By convention, the API functions are exactly the ones:
%
% - not defined by Seaplus (as including seaplus.hrl results, as a side
% effect, in defining start/0 and others)
%
% - and with a spec (so that the user still can opt out a function by not
% defining a spec for it; then this function will not be part of the Seaplus
% binding)
%
% Such selected functions may or may not be defined; then, respectively,
% either Seaplus will re-use the already provided implementation once
% transformed, or generate one from scratch for them.
% All collected module-level function information:
AllFunInfos = table:values( FunctionTable ),
% Seaplus additions (are included in AllFunInfos):
SeaplusFunIds = get_seaplus_function_ids(),
% All the functions selected to form the binding API:
SelectedFunInfos =
select_for_binding( AllFunInfos, SeaplusFunIds, _Acc=[] ),
% We then order the returned function_info records based on the location of
% their spec (so that their IDs correspond to their in-source order):
%
% (we rely on the fact that a function_info is a record whose 6th (i.e. 7
% minus 1 for the record tag) field is the located spec, which is a pair
% whose order is by rule determined first by its first element - which is
% the spec location)
%
OrderedSelected = lists:keysort( _Index=7, SelectedFunInfos ),
% Key in the process dictionary under which the service port will be stored:
PortDictKey = get_port_dict_key_for( ModuleInfo ),
%trace_bridge:debug_fmt( "Will store the service port under the "
% "'~ts' key in the process dictionary.", [ PortDictKey ] ),
MarkerTable = ModuleInfo#module_info.markers,
ExportLoc = ast_info:get_default_export_function_location( MarkerTable ),
DefLoc = table:get_value( definition_functions_marker, MarkerTable ),
% Now that the order is known, we can generate or transform these API
% functions:
%
post_process_fun_infos( OrderedSelected, PortDictKey, ExportLoc, DefLoc ).
-doc """
Selects the functions to be included in the binding.
Too early to determine whether they should be generated or transformed (i.e. to
look at their clauses), we need to number them first.
(helper)
""".
select_for_binding( _AllFunInfos=[], _SeaplusFunIds, Acc ) ->
Acc;
% No spec, hence not selected:
%select_for_binding( [ _FInfo | T ], SeaplusFunIds, Acc ) ->
select_for_binding( [ #function_info{ %name=Name,
%arity=Arity,
spec=undefined } | T ],
SeaplusFunIds, Acc ) ->
%trace_bridge:debug_fmt( "~ts/~B skipped for binding (no spec).",
% [ Name, Arity ] ),
select_for_binding( T, SeaplusFunIds, Acc );
% A spec is available here:
select_for_binding( [ FInfo=#function_info{ name=Name,
arity=Arity } | T ],
SeaplusFunIds, Acc ) ->
FunId = { Name, Arity },
case lists:member( FunId, SeaplusFunIds ) of