forked from erlang/otp
/
asn1ct.erl
2594 lines (2363 loc) · 82 KB
/
asn1ct.erl
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
%% vim: tabstop=8:shiftwidth=4
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2012. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(asn1ct).
%% Compile Time functions for ASN.1 (e.g ASN.1 compiler).
%%-compile(export_all).
%% Public exports
-export([compile/1, compile/2]).
-export([start/0, start/1]).
-export([encode/2, encode/3, decode/3]).
-export([test/1, test/2, test/3, value/2, value/3]).
%% Application internal exports
-export([compile_asn/3,compile_asn1/3,compile_py/3,compile/3,
vsn/0,
get_name_of_def/1,get_pos_of_def/1]).
-export([read_config_data/1,get_gen_state_field/1,get_gen_state/0,
partial_inc_dec_toptype/1,save_gen_state/1,update_gen_state/2,
get_tobe_refed_func/1,reset_gen_state/0,is_function_generated/1,
generated_refed_func/1,next_refed_func/0,pop_namelist/0,
next_namelist_el/0,update_namelist/1,step_in_constructed/0,
add_tobe_refed_func/1,add_generated_refed_func/1,
maybe_rename_function/3,latest_sindex/0,current_sindex/0,
set_current_sindex/1,next_sindex/0,maybe_saved_sindex/2,
parse_and_save/2,verbose/3,warning/3,warning/4,error/3]).
-include("asn1_records.hrl").
-include_lib("stdlib/include/erl_compile.hrl").
-include_lib("kernel/include/file.hrl").
-import(asn1ct_gen_ber_bin_v2,[encode_tag_val/3,decode_class/1]).
-ifndef(vsn).
-define(vsn,"0.0.1").
-endif.
-define(unique_names,0).
-define(dupl_uniquedefs,1).
-define(dupl_equaldefs,2).
-define(dupl_eqdefs_uniquedefs,?dupl_equaldefs bor ?dupl_uniquedefs).
-define(CONSTRUCTED, 2#00100000).
%% macros used for partial decode commands
-define(CHOOSEN,choosen).
-define(SKIP,skip).
-define(SKIP_OPTIONAL,skip_optional).
%% macros used for partial incomplete decode commands
-define(MANDATORY,mandatory).
-define(DEFAULT,default).
-define(OPTIONAL,opt).
-define(OPTIONAL_UNDECODED,opt_undec).
-define(PARTS,parts).
-define(UNDECODED,undec).
-define(ALTERNATIVE,alt).
-define(ALTERNATIVE_UNDECODED,alt_undec).
-define(ALTERNATIVE_PARTS,alt_parts).
%-define(BINARY,bin).
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This is the interface to the compiler
%%
%%
compile(File) ->
compile(File,[]).
compile(File,Options) when is_list(Options) ->
case lists:member(driver, Options) of %% remove me in R16A!
true ->
io:format("Warning: driver option is obsolete and will be removed in R16A, use nif instead!");
false ->
ok
end,
Options1 = optimize_ber_bin(Options),
Options2 = includes(File,Options1),
Includes = strip_includes(Options2),
in_process(fun() -> compile_proc(File, Includes, Options2) end).
compile_proc(File, Includes, Options) ->
case input_file_type(File, Includes) of
{single_file, SuffixedFile} -> %% "e.g. "/tmp/File.asn"
compile1(SuffixedFile, Options);
{multiple_files_file, SetBase, FileName} ->
case get_file_list(FileName, Includes) of
FileList when is_list(FileList) ->
compile_set(SetBase, FileList, Options);
Err ->
Err
end;
Err = {input_file_error, _Reason} ->
{error, Err}
end.
compile1(File,Options) when is_list(Options) ->
verbose("Erlang ASN.1 version ~p compiling ~p ~n",[?vsn,File],Options),
verbose("Compiler Options: ~p~n",[Options],Options),
Ext = filename:extension(File),
Base = filename:basename(File,Ext),
OutFile = outfile(Base,"",Options),
DbFile = outfile(Base,"asn1db",Options),
Includes = [I || {i,I} <- Options],
EncodingRule = get_rule(Options),
asn1ct_table:new(asn1_functab),
Continue1 = scan(File,Options),
Continue2 = parse(Continue1,File,Options),
Continue3 = check(Continue2,File,OutFile,Includes,EncodingRule,
DbFile,Options,[]),
Continue4 = generate(Continue3,OutFile,EncodingRule,Options),
asn1ct_table:delete(asn1_functab),
Ret = compile_erl(Continue4,OutFile,Options),
case inline(is_inline(Options),
inline_output(Options,filename:rootname(File)),
lists:concat([OutFile,".erl"]),Options) of
false ->
Ret;
InlineRet ->
InlineRet
end.
%%****************************************************************************%%
%% functions dealing with compiling of several input files to one output file %%
%%****************************************************************************%%
%%%
%% inline/4
%% merges the resulting erlang modules with
%% the appropriate run-time modules so the resulting module contains all
%% run-time asn1 functionality. Then compiles the resulting file to beam code.
%% The merging is done by the igor module. If this function is used in older
%% versions than R10B the igor module, part of user contribution syntax_tools,
%% must be provided. It is possible to pass options for the ASN1 compiler
%% Types:
%% Name -> atom()
%% Modules -> [filename()]
%% Options -> [term()]
%% filename() -> file:filename()
inline(true,Name,Module,Options) ->
RTmodule = get_runtime_mod(Options),
IgorOptions = igorify_options(remove_asn_flags(Options)),
IgorName = list_to_atom(filename:rootname(filename:basename(Name))),
% io:format("*****~nName: ~p~nModules: ~p~nIgorOptions: ~p~n*****~n",
% [IgorName,Modules++RTmodule,IgorOptions]),
verbose("Inlining modules: ~p in ~p~n",[[Module]++RTmodule,IgorName],Options),
case catch igor:merge(IgorName,[Module]++RTmodule,[{preprocess,true},{stubs,false},{backups,false}]++IgorOptions) of
{'EXIT',{undef,Reason}} -> %% module igor first in R10B
error("Module igor in syntax_tools must be available:~n~p~n",
[Reason],Options),
{error,'no_compilation'};
{'EXIT',Reason} ->
error("Merge by igor module failed due to ~p~n",[Reason],Options),
{error,'no_compilation'};
_ ->
%% io:format("compiling output module: ~p~n",[generated_file(Name,IgorOptions)]),
erl_compile(generated_file(Name,IgorOptions),Options)
end;
inline(_,_,_,_) ->
false.
%% compile_set/3 merges and compiles a number of asn1 modules
%% specified in a .set.asn file to one .erl file.
compile_set(SetBase,Files,Options)
when is_list(hd(Files)),is_list(Options) ->
%% case when there are several input files in a list
verbose("Erlang ASN.1 version ~p compiling ~p ~n",[?vsn,Files],Options),
verbose("Compiler Options: ~p~n",[Options],Options),
OutFile = outfile(SetBase,"",Options),
DbFile = outfile(SetBase,"asn1db",Options),
Includes = [I || {i,I} <- Options],
EncodingRule = get_rule(Options),
asn1ct_table:new(asn1_functab),
ScanRes = scan_set(Files,Options),
ParseRes = parse_set(ScanRes,Options),
Result =
case [X||X <- ParseRes,element(1,X)==true] of
[] -> %% all were false, time to quit
lists:map(fun(X)->element(2,X) end,ParseRes);
ParseRes -> %% all were true, continue with check
InputModules =
lists:map(
fun(F)->
E = filename:extension(F),
B = filename:basename(F,E),
if
is_list(B) -> list_to_atom(B);
true -> B
end
end,
Files),
check_set(ParseRes,SetBase,OutFile,Includes,
EncodingRule,DbFile,Options,InputModules);
Other ->
{error,{'unexpected error in scan/parse phase',
lists:map(fun(X)->element(3,X) end,Other)}}
end,
asn1ct_table:delete(asn1_functab),
Result.
check_set(ParseRes,SetBase,OutFile,Includes,EncRule,DbFile,
Options,InputModules) ->
MergedModule = merge_modules(ParseRes,SetBase),
SetM = MergedModule#module{name=SetBase},
Continue1 = check({true,SetM},SetBase,OutFile,Includes,EncRule,DbFile,
Options,InputModules),
Continue2 = generate(Continue1,OutFile,EncRule,Options),
asn1ct_table:delete([renamed_defs, original_imports, automatic_tags]),
Ret = compile_erl(Continue2,OutFile,Options),
case inline(is_inline(Options),
inline_output(Options,filename:rootname(OutFile)),
lists:concat([OutFile,".erl"]),Options) of
false ->
Ret;
InlineRet ->
InlineRet
end.
%% merge_modules/2 -> returns a module record where the typeorval lists are merged,
%% the exports lists are merged, the imports lists are merged when the
%% elements come from other modules than the merge set, the tagdefault
%% field gets the shared value if all modules have same tagging scheme,
%% otherwise a tagging_error exception is thrown,
%% the extensiondefault ...(not handled yet).
merge_modules(ParseRes,CommonName) ->
ModuleList = lists:map(fun(X)->element(2,X) end,ParseRes),
NewModuleList = remove_name_collisions(ModuleList),
case asn1ct_table:size(renamed_defs) of
0 -> asn1ct_table:delete(renamed_defs);
_ -> ok
end,
save_imports(NewModuleList),
TypeOrVal = lists:append(lists:map(fun(X)->X#module.typeorval end,
NewModuleList)),
InputMNameList = lists:map(fun(X)->X#module.name end,
NewModuleList),
CExports = common_exports(NewModuleList),
ImportsModuleNameList = lists:map(fun(X)->
{X#module.imports,
X#module.name} end,
NewModuleList),
%% ImportsModuleNameList: [{Imports,ModuleName},...]
%% Imports is a tuple {imports,[#'SymbolsFromModule'{},...]}
CImports = common_imports(ImportsModuleNameList,InputMNameList),
TagDefault = check_tagdefault(NewModuleList),
#module{name=CommonName,tagdefault=TagDefault,exports=CExports,
imports=CImports,typeorval=TypeOrVal}.
%% causes an exit if duplicate definition names exist in a module
remove_name_collisions(Modules) ->
asn1ct_table:new(renamed_defs),
%% Name duplicates in the same module is not allowed.
lists:foreach(fun exit_if_nameduplicate/1,Modules),
%% Then remove duplicates in different modules and return the
%% new list of modules.
remove_name_collisions2(Modules,[]).
%% For each definition in the first module in module list, find
%% all definitons with same name and rename both definitions in
%% the first module and in rest of modules
remove_name_collisions2([M|Ms],Acc) ->
TypeOrVal = M#module.typeorval,
MName = M#module.name,
%% Test each name in TypeOrVal on all modules in Ms
{NewM,NewMs} = remove_name_collisions2(MName,TypeOrVal,Ms,[]),
remove_name_collisions2(NewMs,[M#module{typeorval=NewM}|Acc]);
remove_name_collisions2([],Acc) ->
finished_warn_prints(),
Acc.
%% For each definition in list of defs find definitions in (rest of)
%% modules that have same name. If duplicate was found rename def.
%% Test each name in [T|Ts] on all modules in Ms
remove_name_collisions2(ModName,[T|Ts],Ms,Acc) ->
Name = get_name_of_def(T),
case discover_dupl_in_mods(Name,T,Ms,[],?unique_names) of
{_,?unique_names} -> % there was no name collision
remove_name_collisions2(ModName,Ts,Ms,[T|Acc]);
{NewMs,?dupl_uniquedefs} -> % renamed defs in NewMs
%% rename T
NewT = set_name_of_def(ModName,Name,T), %rename def
warn_renamed_def(ModName,get_name_of_def(NewT),Name),
asn1ct_table:insert(renamed_defs,
{get_name_of_def(NewT), Name, ModName}),
remove_name_collisions2(ModName,Ts,NewMs,[NewT|Acc]);
{NewMs,?dupl_equaldefs} -> % name duplicates, but identical defs
%% keep name of T
warn_kept_def(ModName,Name),
remove_name_collisions2(ModName,Ts,NewMs,[T|Acc]);
{NewMs,?dupl_eqdefs_uniquedefs} ->
%% keep name of T, renamed defs in NewMs
warn_kept_def(ModName,Name),
remove_name_collisions2(ModName,Ts,NewMs,[T|Acc])
end;
remove_name_collisions2(_,[],Ms,Acc) ->
{Acc,Ms}.
%% Name is the name of a definition. If a definition with the same name
%% is found in the modules Ms the definition will be renamed and returned.
discover_dupl_in_mods(Name,Def,[M=#module{name=N,typeorval=TorV}|Ms],
Acc,AnyRenamed) ->
Fun = fun(T,RenamedOrDupl)->
case {get_name_of_def(T),compare_defs(Def,T)} of
{Name,not_equal} ->
%% rename def
NewT=set_name_of_def(N,Name,T),
warn_renamed_def(N,get_name_of_def(NewT),Name),
asn1ct_table:insert(renamed_defs,
{get_name_of_def(NewT), Name, N}),
{NewT,?dupl_uniquedefs bor RenamedOrDupl};
{Name,equal} ->
%% delete def
warn_deleted_def(N,Name),
{[],?dupl_equaldefs bor RenamedOrDupl};
_ ->
{T,RenamedOrDupl}
end
end,
{NewTorV,NewAnyRenamed} = lists:mapfoldl(Fun,AnyRenamed,TorV),
%% have to flatten the NewTorV to remove any empty list elements
discover_dupl_in_mods(Name,Def,Ms,
[M#module{typeorval=lists:flatten(NewTorV)}|Acc],
NewAnyRenamed);
discover_dupl_in_mods(_,_,[],Acc,AnyRenamed) ->
{Acc,AnyRenamed}.
warn_renamed_def(ModName,NewName,OldName) ->
maybe_first_warn_print(),
io:format("NOTICE: The ASN.1 definition in module ~p with name ~p has been renamed in generated module. New name is ~p.~n",[ModName,OldName,NewName]).
warn_deleted_def(ModName,DefName) ->
maybe_first_warn_print(),
io:format("NOTICE: The ASN.1 definition in module ~p with name ~p has been deleted in generated module.~n",[ModName,DefName]).
warn_kept_def(ModName,DefName) ->
maybe_first_warn_print(),
io:format("NOTICE: The ASN.1 definition in module ~p with name ~p has kept its name due to equal definition as duplicate.~n",[ModName,DefName]).
maybe_first_warn_print() ->
case get(warn_duplicate_defs) of
undefined ->
put(warn_duplicate_defs,true),
io:format("~nDue to multiple occurrences of a definition name in "
"multi-file compiled files:~n");
_ ->
ok
end.
finished_warn_prints() ->
put(warn_duplicate_defs,undefined).
exit_if_nameduplicate(#module{typeorval=TorV}) ->
exit_if_nameduplicate(TorV);
exit_if_nameduplicate([]) ->
ok;
exit_if_nameduplicate([Def|Rest]) ->
Name=get_name_of_def(Def),
exit_if_nameduplicate2(Name,Rest),
exit_if_nameduplicate(Rest).
exit_if_nameduplicate2(Name,Rest) ->
Pred=fun(Def)->
case get_name_of_def(Def) of
Name -> true;
_ -> false
end
end,
case lists:any(Pred,Rest) of
true ->
throw({error,{"more than one definition with same name",Name}});
_ ->
ok
end.
compare_defs(D1,D2) ->
compare_defs2(unset_pos_mod(D1),unset_pos_mod(D2)).
compare_defs2(D,D) ->
equal;
compare_defs2(_,_) ->
not_equal.
unset_pos_mod(Def) when is_record(Def,typedef) ->
Def#typedef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,classdef) ->
Def#classdef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,valuedef) ->
Def#valuedef{pos=undefined,module=undefined};
unset_pos_mod(Def) when is_record(Def,ptypedef) ->
Def#ptypedef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,pvaluedef) ->
Def#pvaluedef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,pvaluesetdef) ->
Def#pvaluesetdef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,pobjectdef) ->
Def#pobjectdef{pos=undefined};
unset_pos_mod(Def) when is_record(Def,pobjectsetdef) ->
Def#pobjectsetdef{pos=undefined}.
get_pos_of_def(#typedef{pos=Pos}) ->
Pos;
get_pos_of_def(#classdef{pos=Pos}) ->
Pos;
get_pos_of_def(#valuedef{pos=Pos}) ->
Pos;
get_pos_of_def(#ptypedef{pos=Pos}) ->
Pos;
get_pos_of_def(#pvaluedef{pos=Pos}) ->
Pos;
get_pos_of_def(#pvaluesetdef{pos=Pos}) ->
Pos;
get_pos_of_def(#pobjectdef{pos=Pos}) ->
Pos;
get_pos_of_def(#pobjectsetdef{pos=Pos}) ->
Pos;
get_pos_of_def(_) ->
undefined.
get_name_of_def(#typedef{name=Name}) ->
Name;
get_name_of_def(#classdef{name=Name}) ->
Name;
get_name_of_def(#valuedef{name=Name}) ->
Name;
get_name_of_def(#ptypedef{name=Name}) ->
Name;
get_name_of_def(#pvaluedef{name=Name}) ->
Name;
get_name_of_def(#pvaluesetdef{name=Name}) ->
Name;
get_name_of_def(#pobjectdef{name=Name}) ->
Name;
get_name_of_def(#pobjectsetdef{name=Name}) ->
Name;
get_name_of_def(_) ->
undefined.
set_name_of_def(ModName,Name,OldDef) ->
NewName = list_to_atom(lists:concat([Name,ModName])),
case OldDef of
#typedef{} -> OldDef#typedef{name=NewName};
#classdef{} -> OldDef#classdef{name=NewName};
#valuedef{} -> OldDef#valuedef{name=NewName};
#ptypedef{} -> OldDef#ptypedef{name=NewName};
#pvaluedef{} -> OldDef#pvaluedef{name=NewName};
#pvaluesetdef{} -> OldDef#pvaluesetdef{name=NewName};
#pobjectdef{} -> OldDef#pobjectdef{name=NewName};
#pobjectsetdef{} -> OldDef#pobjectsetdef{name=NewName}
end.
save_imports(ModuleList)->
Fun = fun(M) ->
case M#module.imports of
{_,[]} -> [];
{_,I} ->
{M#module.name,I}
end
end,
ImportsList = lists:map(Fun,ModuleList),
case lists:flatten(ImportsList) of
[] ->
ok;
ImportsList2 ->
asn1ct_table:new(original_imports),
lists:foreach(fun(X) -> asn1ct_table:insert(original_imports, X) end,
ImportsList2)
end.
common_exports(ModuleList) ->
%% if all modules exports 'all' then export 'all',
%% otherwise export each typeorval name
case lists:filter(fun(X)->
element(2,X#module.exports) /= all
end,
ModuleList) of
[]->
{exports,all};
ModsWithExpList ->
CExports1 =
lists:append(lists:map(fun(X)->element(2,X#module.exports) end,
ModsWithExpList)),
CExports2 = export_all(lists:subtract(ModuleList,ModsWithExpList)),
{exports,CExports1++CExports2}
end.
export_all([])->[];
export_all(ModuleList) ->
ExpList =
lists:map(
fun(M)->
TorVL=M#module.typeorval,
MName = M#module.name,
lists:map(
fun(Def)->
case Def of
T when is_record(T,typedef)->
#'Externaltypereference'{pos=0,
module=MName,
type=T#typedef.name};
V when is_record(V,valuedef) ->
#'Externalvaluereference'{pos=0,
module=MName,
value=V#valuedef.name};
C when is_record(C,classdef) ->
#'Externaltypereference'{pos=0,
module=MName,
type=C#classdef.name};
P when is_record(P,ptypedef) ->
#'Externaltypereference'{pos=0,
module=MName,
type=P#ptypedef.name};
PV when is_record(PV,pvaluesetdef) ->
#'Externaltypereference'{pos=0,
module=MName,
type=PV#pvaluesetdef.name};
PO when is_record(PO,pobjectdef) ->
#'Externalvaluereference'{pos=0,
module=MName,
value=PO#pobjectdef.name}
end
end,
TorVL)
end,
ModuleList),
lists:append(ExpList).
%% common_imports/2
%% IList is a list of tuples, {Imports,MName}, where Imports is the imports of
%% the module with name MName.
%% InputMNameL holds the names of all merged modules.
%% Returns an import tuple with a list of imports that are external the merged
%% set of modules.
common_imports(IList,InputMNameL) ->
SetExternalImportsList = remove_in_set_imports(IList,InputMNameL,[]),
{imports,remove_import_doubles(SetExternalImportsList)}.
check_tagdefault(ModList) ->
case have_same_tagdefault(ModList) of
{true,TagDefault} -> TagDefault;
{false,TagDefault} ->
asn1ct_table:new(automatic_tags),
save_automatic_tagged_types(ModList),
TagDefault
end.
have_same_tagdefault([#module{tagdefault=T}|Ms]) ->
have_same_tagdefault(Ms,{true,T}).
have_same_tagdefault([],TagDefault) ->
TagDefault;
have_same_tagdefault([#module{tagdefault=T}|Ms],TDefault={_,T}) ->
have_same_tagdefault(Ms,TDefault);
have_same_tagdefault([#module{tagdefault=T1}|Ms],{_,T2}) ->
have_same_tagdefault(Ms,{false,rank_tagdef([T1,T2])}).
rank_tagdef(L) ->
case lists:member('EXPLICIT',L) of
true -> 'EXPLICIT';
_ -> 'IMPLICIT'
end.
save_automatic_tagged_types([])->
done;
save_automatic_tagged_types([#module{tagdefault='AUTOMATIC',
typeorval=TorV}|Ms]) ->
Fun =
fun(T) ->
asn1ct_table:insert(automatic_tags, {get_name_of_def(T)})
end,
lists:foreach(Fun,TorV),
save_automatic_tagged_types(Ms);
save_automatic_tagged_types([_M|Ms]) ->
save_automatic_tagged_types(Ms).
%% remove_in_set_imports/3 :
%% input: list with tuples of each module's imports and module name
%% respectively.
%% output: one list with same format but each occured import from a
%% module in the input set (IMNameL) is removed.
remove_in_set_imports([{{imports,ImpL},_ModName}|Rest],InputMNameL,Acc) ->
NewImpL = remove_in_set_imports1(ImpL,InputMNameL,[]),
remove_in_set_imports(Rest,InputMNameL,NewImpL++Acc);
remove_in_set_imports([],_,Acc) ->
lists:reverse(Acc).
remove_in_set_imports1([I|Is],InputMNameL,Acc) ->
case I#'SymbolsFromModule'.module of
#'Externaltypereference'{type=MName} ->
case lists:member(MName,InputMNameL) of
true ->
remove_in_set_imports1(Is,InputMNameL,Acc);
false ->
remove_in_set_imports1(Is,InputMNameL,[I|Acc])
end;
_ ->
remove_in_set_imports1(Is,InputMNameL,[I|Acc])
end;
remove_in_set_imports1([],_,Acc) ->
lists:reverse(Acc).
remove_import_doubles([]) ->
[];
%% If several modules in the merge set imports symbols from
%% the same external module it might be doubled.
%% ImportList has #'SymbolsFromModule' elements
remove_import_doubles(ImportList) ->
MergedImportList =
merge_symbols_from_module(ImportList,[]),
%% io:format("MergedImportList: ~p~n",[MergedImportList]),
delete_double_of_symbol(MergedImportList,[]).
merge_symbols_from_module([Imp|Imps],Acc) ->
#'Externaltypereference'{type=ModName} = Imp#'SymbolsFromModule'.module,
IfromModName =
lists:filter(
fun(I)->
case I#'SymbolsFromModule'.module of
#'Externaltypereference'{type=ModName} ->
true;
#'Externalvaluereference'{value=ModName} ->
true;
_ -> false
end
end,
Imps),
NewImps = lists:subtract(Imps,IfromModName),
%% io:format("Imp: ~p~nIfromModName: ~p~n",[Imp,IfromModName]),
NewImp =
Imp#'SymbolsFromModule'{
symbols = lists:append(
lists:map(fun(SL)->
SL#'SymbolsFromModule'.symbols
end,[Imp|IfromModName]))},
merge_symbols_from_module(NewImps,[NewImp|Acc]);
merge_symbols_from_module([],Acc) ->
lists:reverse(Acc).
delete_double_of_symbol([I|Is],Acc) ->
SymL=I#'SymbolsFromModule'.symbols,
NewSymL = delete_double_of_symbol1(SymL,[]),
delete_double_of_symbol(Is,[I#'SymbolsFromModule'{symbols=NewSymL}|Acc]);
delete_double_of_symbol([],Acc) ->
Acc.
delete_double_of_symbol1([TRef=#'Externaltypereference'{type=TrefName}|Rest],Acc)->
NewRest =
lists:filter(fun(S)->
case S of
#'Externaltypereference'{type=TrefName}->
false;
_ -> true
end
end,
Rest),
delete_double_of_symbol1(NewRest,[TRef|Acc]);
delete_double_of_symbol1([VRef=#'Externalvaluereference'{value=VName}|Rest],Acc) ->
NewRest =
lists:filter(fun(S)->
case S of
#'Externalvaluereference'{value=VName}->
false;
_ -> true
end
end,
Rest),
delete_double_of_symbol1(NewRest,[VRef|Acc]);
delete_double_of_symbol1([TRef={#'Externaltypereference'{type=MRef},
#'Externaltypereference'{type=TRef}}|Rest],
Acc)->
NewRest =
lists:filter(
fun(S)->
case S of
{#'Externaltypereference'{type=MRef},
#'Externaltypereference'{type=TRef}}->
false;
_ -> true
end
end,
Rest),
delete_double_of_symbol1(NewRest,[TRef|Acc]);
delete_double_of_symbol1([],Acc) ->
Acc.
scan_set(Files,Options) ->
%% The files in Files already have their relative path and extension
lists:map(
fun(F)->
case scan(F,Options) of
{false,{error,Reason}} ->
throw({error,{'scan error in file:',F,Reason}});
{TrueOrFalse,Res} ->
{TrueOrFalse,Res,F}
end
end,
Files).
parse_set(ScanRes,Options) ->
lists:map(
fun({TorF,Toks,F})->
case parse({TorF,Toks},F,Options) of
{false,{error,Reason}} ->
throw({error,{'parse error in file:',F,Reason}});
{TrueOrFalse,Res} ->
{TrueOrFalse,Res,F}
end
end,
ScanRes).
%%***********************************
scan(File,Options) ->
case asn1ct_tok:file(File) of
{error,Reason} ->
error("~p~n",[Reason],Options),
{false,{error,Reason}};
Tokens ->
case lists:member(ss,Options) of
true -> % we terminate after scan
{false,Tokens};
false -> % continue with next pass
{true,Tokens}
end
end.
parse({true,Tokens},File,Options) ->
%Presult = asn1ct_parser2:parse(Tokens),
%%case lists:member(p1,Options) of
%% true ->
%% asn1ct_parser:parse(Tokens);
%% _ ->
%% asn1ct_parser2:parse(Tokens)
%% end,
case catch asn1ct_parser2:parse(Tokens) of
{error,{{Line,_Mod,Message},_TokTup}} ->
if
is_integer(Line) ->
BaseName = filename:basename(File),
error("syntax error at line ~p in module ~s:~n",
[Line,BaseName],Options);
true ->
error("syntax error in module ~p:~n",
[File],Options)
end,
print_error_message(Message),
{false,{error,Message}};
{error,{Line,_Mod,[Message,Token]}} ->
error("syntax error: ~p ~p at line ~p~n",
[Message,Token,Line],Options),
{false,{error,{Line,[Message,Token]}}};
{ok,M} ->
case lists:member(sp,Options) of
true -> % terminate after parse
{false,M};
false -> % continue with next pass
{true,M}
end;
OtherError ->
error("~p~n",[OtherError],Options)
end;
parse({false,Tokens},_,_) ->
{false,Tokens}.
check({true,M},File,OutFile,Includes,EncodingRule,DbFile,Options,InputMods) ->
start(Includes),
case asn1ct_check:storeindb(#state{erule=EncodingRule},M) of
ok ->
Module = asn1_db:dbget(M#module.name,'MODULE'),
State = #state{mname=Module#module.name,
module=Module#module{typeorval=[]},
erule=EncodingRule,
inputmodules=InputMods,
options=Options,
sourcedir=filename:dirname(File)},
Check = asn1ct_check:check(State,Module#module.typeorval),
case {Check,lists:member(abs,Options)} of
{{error,Reason},_} ->
{false,{error,Reason}};
{{ok,NewTypeOrVal,_},true} ->
NewM = Module#module{typeorval=NewTypeOrVal},
asn1_db:dbput(NewM#module.name,'MODULE',NewM),
pretty2(M#module.name,lists:concat([OutFile,".abs"])),
{false,ok};
{{ok,NewTypeOrVal,GenTypeOrVal},_} ->
NewM = Module#module{typeorval=NewTypeOrVal},
asn1_db:dbput(NewM#module.name,'MODULE',NewM),
asn1_db:dbsave(DbFile,M#module.name),
verbose("--~p--~n",[{generated,DbFile}],Options),
{true,{M,NewM,GenTypeOrVal}}
end;
ErrorList = {error,_} ->
{false,ErrorList}
end;
check({false,M},_,_,_,_,_,_,_) ->
{false,M}.
generate({true,{M,_Module,GenTOrV}},OutFile,EncodingRule,Options) ->
debug_on(Options),
case lists:member(compact_bit_string,Options) of
true -> put(compact_bit_string,true);
_ -> ok
end,
put(encoding_options,Options),
asn1ct_table:new(check_functions),
%% create decoding function names and taglists for partial decode
case specialized_decode_prepare(EncodingRule,M,GenTOrV,Options) of
{error, Reason} -> warning("Error in configuration file: ~n~p~n",
[Reason], Options,
"Error in configuration file");
_ -> ok
end,
Result =
case (catch asn1ct_gen:pgen(OutFile,EncodingRule,
M#module.name,GenTOrV,Options)) of
{'EXIT',Reason2} ->
error("~p~n",[Reason2],Options),
{error,Reason2};
_ ->
ok
end,
debug_off(Options),
put(compact_bit_string,false),
erase(encoding_options),
erase(tlv_format), % used in ber_bin, optimize
erase(class_default_type),% used in ber_bin, optimize
asn1ct_table:delete(check_functions),
case Result of
{error,_} ->
{false,Result};
ok ->
case lists:member(sg,Options) of
true -> % terminate here , with .erl file generated
{false,true};
false ->
{true,true}
end
end;
generate({false,M},_,_,_) ->
{false,M}.
%% parse_and_save parses an asn1 spec and saves the unchecked parse
%% tree in a data base file.
%% Does not support multifile compilation files
parse_and_save(Module,S) ->
Options = S#state.options,
SourceDir = S#state.sourcedir,
Includes = [I || {i,I} <-Options],
Options1 = optimize_ber_bin(Options),
case get_input_file(Module,[SourceDir|Includes]) of
%% search for asn1 source
{file,SuffixedASN1source} ->
case dbfile_uptodate(SuffixedASN1source,Options1) of
false ->
parse_and_save1(S,SuffixedASN1source,Options1,Includes);
_ -> ok
end;
Err ->
warning("could not do a consistency check of the ~p file: no asn1 source file was found.~n",
[lists:concat([Module,".asn1db"])],Options),
{error,{asn1,input_file_error,Err}}
end.
parse_and_save1(S,File,Options,Includes) ->
Ext = filename:extension(File),
Base = filename:basename(File,Ext),
DbFile = outfile(Base,"asn1db",Options),
Continue1 = scan(File,Options),
M =
case parse(Continue1,File,Options) of
{true,Mod} -> Mod;
_ ->
%% io:format("~p~nnow I die!!!!!!!!!!!~n",[File]),
exit({error,{asn1,File,"no such file"}})
end,
% start(["."|Includes]),
start(Includes),
case asn1ct_check:storeindb(S,M) of
ok ->
asn1_db:dbsave(DbFile,M#module.name)
end.
get_input_file(Module,[]) ->
Module;
get_input_file(Module,[I|Includes]) ->
case (catch input_file_type(filename:join([I,Module]))) of
{single_file,FileName} ->
%% case file:read_file_info(FileName) of
%% {ok,_} ->
{file,FileName};
%% _ -> get_input_file(Module,Includes)
%% end;
_ ->
get_input_file(Module,Includes)
end.
dbfile_uptodate(File,Options) ->
EncodingRule = get_rule(Options),
Ext = filename:extension(File),
Base = filename:basename(File,Ext),
DbFile = outfile(Base,"asn1db",Options),
case file:read_file_info(DbFile) of
{error,enoent} ->
false;
{ok,FileInfoDb} ->
%% file exists, check date and finally encodingrule
{ok,FileInfoAsn} = file:read_file_info(File),
case FileInfoDb#file_info.mtime < FileInfoAsn#file_info.mtime of
true ->
%% date of asn1 spec newer than db file
false;
_ ->
%% date ok,check that same erule was used
Obase = case lists:keysearch(outdir, 1, Options) of
{value, {outdir, Odir}} ->
Odir;
_NotFound -> ""
end,
BeamFileName = outfile(Base,"beam",Options),
case file:read_file_info(BeamFileName) of
{ok,_} ->
code:add_path(Obase),
BeamFile = list_to_atom(Base),
BeamInfo = (catch BeamFile:info()),
case catch lists:keysearch(options,1,BeamInfo) of
{value,{options,OldOptions}} ->
case get_rule(OldOptions) of
EncodingRule -> true;
_ -> false
end;
_ -> false
end;
_ -> false
end
end
end.
compile_erl({true,_},OutFile,Options) ->
erl_compile(OutFile,Options);
compile_erl({false,true},_,_) ->
ok;
compile_erl({false,Result},_,_) ->
Result.
input_file_type(Name,I) ->
case input_file_type(Name) of
{error,_} -> input_file_type2(filename:basename(Name),I);
Err={input_file_error,_} -> Err;
Res -> Res
end.
input_file_type2(Name,[I|Is]) ->
case input_file_type(filename:join([I,Name])) of
{error,_} -> input_file_type2(Name,Is);
Err={input_file_error,_} -> Err;
Res -> Res
end;
input_file_type2(Name,[]) ->
input_file_type(Name).
input_file_type([]) ->
{empty_name,[]};
input_file_type(File) ->
case filename:extension(File) of
[] ->
case file:read_file_info(lists:concat([File,".asn1"])) of
{ok,_FileInfo} ->
{single_file, lists:concat([File,".asn1"])};
_Error ->
case file:read_file_info(lists:concat([File,".asn"])) of