-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
xmerl_xsd.erl
5663 lines (5288 loc) · 190 KB
/
xmerl_xsd.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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2006-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%----------------------------------------------------------------------
-module(xmerl_xsd).
-moduledoc """
Interface module for XML Schema validation.
It handles the W3.org [specifications](http://www.w3.org/XML/Schema#dev) of
XML Schema second edition 28 october 2004. For an introduction to
XML Schema please study [part 0](http://www.w3.org/TR/xmlschema-0/).
An XML structure is validated by [`xmerl_xsd:validate/[2,3]`](`validate/2`).
""".
%%----------------------------------------------------------------------
%% Include files
%%----------------------------------------------------------------------
-include("xmerl.hrl").
-include("xmerl_internal.hrl").
-include("xmerl_xsd.hrl").
-include_lib("kernel/include/file.hrl").
%%----------------------------------------------------------------------
%% External exports
%%----------------------------------------------------------------------
-export([validate/2,validate/3,process_validate/2,process_validate/3,
process_schema/1,process_schema/2,
process_schemas/1,process_schemas/2,
state2file/1,state2file/2,file2state/1,format_error/1]).
%%----------------------------------------------------------------------
%% Internal exports
%%----------------------------------------------------------------------
-export([print_table/1]).
%%-export([whitespace/1]).
%%----------------------------------------------------------------------
%% Imports
%%----------------------------------------------------------------------
-import(xmerl_lib,[is_facet/1, is_builtin_simple_type/1, is_xsd_string/1]).
-import(xmerl_xsd_type,[facet_fun/2]).
-import(lists,[reverse/1,reverse/2,foldl/3,member/2,filter/2,flatten/1,map/2,
splitwith/2,mapfoldl/3,keysearch/3,keymember/3,
keyreplace/4,keydelete/3]).
%%----------------------------------------------------------------------
%% Types
%%----------------------------------------------------------------------
-compile({nowarn_hidden_doc, [xsd_state/0]}).
-doc hidden.
-type xsd_state() :: #xsd_state{}.
-doc """
The global state of the validator.
It is represented by the `#xsd_state{}` record.
""".
-type global_state() :: xsd_state().
-doc """
Options that allow to customize the behaviour of the validation.
Possible options are :
<dl>
<dt><code>{tab2file,boolean()}</code></dt>
<dd>Enables saving of abstract structure on file for debugging
purpose.</dd>
<dt><code>{xsdbase,filename()}</code></dt>
<dd>XSD Base directory.</dd>
<dt><code>{fetch_fun,FetchFun}</code></dt>
<dd>Call back function to fetch an external resource.</dd>
<dt><code>{fetch_path,PathList}</code></dt>
<dd>PathList is a list of directories to search when fetching files.
If the file in question is not in the fetch_path, the URI will
be used as a file name.</dd>
<dt><code>{state,State}</code></dt>
<dd>It is possible by this option to provide a state with process
information from an earlier validation.</dd>
</dl>
""".
-type option_list() :: [{xsdbase,filename()} |
{atom(),term()}].
-type filename() :: string().
%%======================================================================
%% Functions
%%======================================================================
-doc(#{ equiv => validate(Element, State, []) }).
-spec validate(Element :: xmerl:element(), State :: global_state()) -> _.
validate(Xml,State) ->
validate(Xml,State,[]).
-doc """
Validate a parsed well-formed XML element (`Element`).
A call to `validate/2` or `validate/3` must provide a well formed
parsed XML [`Element :: #xmlElement{}`](`t:xmerl:xmlElement/0`)
and a State, `t:global_state/0`, which holds necessary information
from an already processed schema. Thus validate enables reuse
of the schema information and therefore if one shall validate
several times towards the same schema it reduces time consumption.
The result, `ValidElement`, is the valid element that conforms to the
post-schema-validation infoset. When the validator finds an error it tries to
continue and reports a list of all errors found. In those cases an unexpected
error is found it may cause a single error reason.
Usage example:
``` erlang
1>{E,_} = xmerl_scan:file("my_XML_document.xml").
2>{ok,S} = xmerl_xsd:process_schema("my_XML_Schema.xsd").
3>{E2,_} = xmerl_xsd:validate(E,S).
```
Observe that E2 may differ from E if for instance there are default values
defined in `my_XML_Schema.xsd`.
""".
-spec validate(Element, global_state(), Options) -> Result when
Element :: xmerl:xmlElement(),
Options :: option_list(),
Result :: {ValidElement,global_state()} | {error,Reasons},
ValidElement :: xmerl:xmlElement(),
Reasons :: [ErrorReason] | ErrorReason,
ErrorReason :: term().
validate(Xml,State,Opts) when is_record(State,xsd_state) ->
S2 = initiate_state2(State,Opts),
S3 = validation_options(S2,Opts),
validate3(S3#xsd_state.schema_name,Xml,S3).
-doc """
Equivalent to [`state2file(State, SchemaName)`](`state2file/2`).
`SchemaName` is the name of the schema in `State`.
""".
-spec state2file(State :: global_state()) -> ok | {error,Reason} when
Reason :: term().
state2file(S=#xsd_state{schema_name=SN}) ->
state2file(S,filename:rootname(SN)).
-doc """
Save the schema processing state to a file.
Saves the schema state with all information of the processed schema in a file.
You can provide the file name for the saved state. FileName is saved with the
`.xss` extension added.
""".
-spec state2file(global_state(), FileName :: string()) ->
ok | {error,Reason} when
Reason :: term().
state2file(S,FileName) when is_record(S,xsd_state) ->
save_xsd_state(S),
case catch ets:tab2file(S#xsd_state.table,lists:append(FileName,".xss")) of
{'EXIT',Reason} ->
{error,{[],?MODULE,Reason}};
Ret -> Ret
end.
-doc """
Read the schema processing state from a file.
Reads the schema state with all information of the processed schema from
a file created with `state2file/[1,2]`. The format of this file is internal.
The state can then be used validating an XML document.
""".
-spec file2state(FileName :: string()) ->
{ok,State} | {error,Reason} when
State :: global_state(),
Reason :: term().
file2state(FileName) ->
case catch ets:file2tab(FileName) of
{ok,Tab} ->
case load_xsd_state(Tab) of
[{state,S}] when is_record(S,xsd_state) ->
xmerl_xsd_vsn_check(S);
%% {ok,S};
Other ->
{error,{[],?MODULE,{incomplete_file,FileName,Other}}}
end;
{error,Reason} ->
{error,{[],?MODULE,Reason}};
Other ->
{error,{[],?MODULE,Other}}
end.
save_xsd_state(S) ->
catch ets:insert(S#xsd_state.table,{state,S}).
load_xsd_state(Table) ->
catch ets:lookup(Table,state).
xmerl_xsd_vsn() ->
case lists:keysearch(vsn,1,xmerl_xsd:module_info(attributes)) of
{value,{_,MD5_VSN}} ->
MD5_VSN;
_ ->
undefined
end.
xmerl_xsd_vsn_check(S=#xsd_state{vsn=MD5_VSN}) ->
case [V||{vsn,V}<-xmerl_xsd:module_info(attributes)] of
[MD5_VSN] ->
{ok,S};
_ ->
{error,{[],?MODULE,{different_version_of_xmerl_xsd_module_used,
state_not_reliable}}}
end.
-doc(#{ equiv => process_validate(Schema, Element, []) }).
-spec process_validate(Schema :: string(), Element :: xmerl:element()) -> _.
process_validate(Schema,Xml) ->
process_validate(Schema,Xml,[]).
-doc """
Validate a parsed well-formed XML element towards an XML schema.
Validates in two steps. First it processes the schema, saves the type and
structure info in an ETS table and then validates the element towards the
schema.
Usage example:
`1>{E,_} = xmerl_scan:file("my_XML_document.xml").`
`2>{E2,_} = xmerl_xsd:process_validate("my_XML_Schema.xsd",E).`
Observe that E2 may differ from E if for instance there are default values
defined in `my_XML_Schema.xsd`.
""".
-spec process_validate(Schema, Element, Options) -> Result when
Schema :: string(),
Element :: xmerl:element(),
Options :: option_list(),
Result :: {ValidElement,global_state()} | {error,Reasons},
ValidElement :: xmerl:element(),
Reasons :: [Reason :: term()] | Reason :: term().
process_validate(Schema,Xml,Opts) ->
TargetNamespace = target_namespace(Xml),
case Schema of
[H|_] when is_list(H); is_tuple(H) ->
case process_schemas(Schema,
[{target_namespace,TargetNamespace}|Opts]) of
{ok,S} ->
S2 = validation_options(S,Opts),
validate3(S2#xsd_state.schema_name,Xml,S2);
Err ->
Err
end;
_ ->
process_validate2(xmerl_scan:file(Schema),Schema,Xml,Opts)
end.
process_validate2(Err={error,_},_,_,_) ->
Err;
process_validate2({SE,_},Schema,Xml,Opts) ->
S = initiate_state(Opts,Schema),
S1 = validate_schema(SE,S),
S2 = validate_schema_ph2(S1),
S3 = schema_concistence_checks(S2),
S4 = validation_options(S3,Opts),
validate3(Schema,Xml,S4).
validate3(Schema, Xml,S =#xsd_state{errors=[]}) ->
Ret = {_, S2} =
case catch validate_xml(Xml, S) of
_Err = {error, Reason} ->
{Xml, acc_errs(S, Reason)};
{'EXIT', Reason} ->
{Xml, acc_errs(S, {error_path(Xml, Xml#xmlElement.name), ?MODULE,
{undefined, {internal_error, Reason}}})};
{XML2, Rest, Sx} ->
case lists:dropwhile(fun(X) when is_record(X, xmlComment) -> true; (_) -> false end, Rest) of
[] ->
case XML2 of
[XML3] ->
{XML3,Sx};
XML3 ->
{XML3,Sx}
end;
UnValidated ->
{Xml,acc_errs(Sx,{error_path(UnValidated,Xml#xmlElement.name),?MODULE,
{unvalidated_rest,UnValidated}})}
end
end,
save_to_file(S2,filename:rootname(Schema)++".tab2"),
case S2#xsd_state.errors of
[] ->
Ret;
L ->
%%delete_table(S2),
return_error(L)
end;
validate3(_,_,S) ->
return_schema_error(S#xsd_state.errors).
-doc(#{ equiv => process_schema(Schema, []) }).
-spec process_schema(Schema :: string()) -> _.
process_schema(Schema) ->
process_schema(Schema,[]).
-doc """
Read an XML schema and check that it is valid.
Reads the referenced XML schema and checks that it is valid. Returns the
`t:global_state/0` with schema info or an error reason. The error reason
may be a list of several errors or a single error encountered
during the processing.
""".
-spec process_schema(Schema :: string(), Options :: option_list()) ->
{ok, State} | {error, Reasons} when
State :: global_state(),
Reasons :: [Reason :: term()] | Reason :: term().
process_schema(Schema,Options) when is_list(Options) ->
State = initiate_state(Options,Schema),
process_schema2(Schema, State).
%%
process_schema2(Schema, State=#xsd_state{fetch_fun=Fetch})->
case Fetch(Schema, State) of
{ok,{file,File},_} ->
process_schema2(xmerl_scan:file(File), State, Schema);
{ok,{string,Str},_} ->
process_schema2(xmerl_scan:string(Str), State, Schema);
{ok,[],_} ->
{error,enoent};
Err ->
Err
end.
%%
process_schema2(Err={error,_},_,_) ->
Err;
process_schema2({SE,_},State,_Schema) ->
S1 = validate_schema(SE,State),
S2 = validate_schema_ph2(S1),
case schema_concistence_checks(S2) of
S3 = #xsd_state{errors=[]} ->
{ok,S3};
S3 ->
delete_table(S3),
return_error(S3#xsd_state.errors)
end.
-doc(#{ equiv => process_schemas(Schemas, []) }).
-spec process_schemas(Schemas :: list()) -> _.
process_schemas(Schemas) ->
process_schemas(Schemas,[]).
-doc """
Read XML schemas and check that they are valid.
Reads the referenced XML schemas and controls they are valid. Returns the
`t:global_state/0` with schema info or an error reason. The error reason may be
a list of several errors or a single error encountered during the processing.
""".
-spec process_schemas(Schemas, Options) ->
{ok, State} | {error, Reasons} when
Schemas :: nonempty_list({NameSpace, Schema}),
Options :: option_list(),
NameSpace :: term(),
Schema :: string(),
State :: global_state(),
Reasons :: [Reason :: term()] | Reason :: term().
process_schemas(Schemas=[{_,Schema}|_],Options) when is_list(Options) ->
State = initiate_state(Options,Schema),
process_schemas2(Schemas, State).
%%%
process_schemas2([{_NS,Schema}|Rest],State=#xsd_state{fetch_fun=Fetch}) ->
Res=
case Fetch(Schema,State) of
{ok,{file,File},_} ->
process_schema2(xmerl_scan:file(File),State,Schema);
{ok,{string,Str},_} ->
process_schema2(xmerl_scan:string(Str),State,Schema);
{ok,[],_} ->
{ok,State};
Err ->
Err
end,
case Res of
{ok,S2} ->
process_schemas2(Rest,S2);
_ ->
Res
end;
process_schemas2([],State=#xsd_state{}) ->
{ok,State}.
initiate_state(Opts,Schema) ->
XSDBase = filename:dirname(Schema),
{{state,S},RestOpts}=new_state(Opts),
S2 = create_tables(S),
initiate_state2(S2#xsd_state{schema_name = Schema, xsd_base=XSDBase,
fetch_fun = fun fetch/2},
RestOpts).
initiate_state2(S,[]) ->
S;
initiate_state2(S,[{tab2file,Bool}|T]) ->
initiate_state2(S#xsd_state{tab2file=Bool},T);
initiate_state2(S,[{xsdbase, XSDBase}|T]) ->
initiate_state2(S#xsd_state{xsd_base=XSDBase, external_xsd_base=true},T);
initiate_state2(S,[{fetch_fun,FetchFun}|T]) ->
initiate_state2(S#xsd_state{fetch_fun=FetchFun},T);
initiate_state2(S,[{fetch_path,FetchPath}|T]) ->
initiate_state2(S#xsd_state{fetch_path=FetchPath},T);
initiate_state2(S,[{schema_preprocessed,Bool}|T]) ->
initiate_state2(S#xsd_state{schema_preprocessed=Bool},T);
initiate_state2(S,[{target_namespace,_NS}|T]) ->
%% initiate_state2(S#xsd_state{targetNamespace=if_list_to_atom(NS)},T);
initiate_state2(S,T); %% used in validation phase
initiate_state2(S,[H|T]) ->
error_msg("~w: invalid option: ~p~n",[?MODULE, H]),
initiate_state2(S,T).
validation_options(S,[{target_namespace,NS}|T]) ->
validation_options(S#xsd_state{targetNamespace=if_list_to_atom(NS)},T);
validation_options(S,[_H|T]) ->
validation_options(S,T);
validation_options(S,[]) ->
S.
new_state(Opts) ->
XSD_VSN = xmerl_xsd_vsn(),
keysearch_delete(state,1,Opts,{state,#xsd_state{vsn=XSD_VSN}}).
%% validate_schema/2 traverses the shema element to save necessary
%% information as defined elements and types.
validate_schema(E=#xmlElement{},
S) ->
%% namespace is always a xmlNamespace record, attributes a list of
%% #xmlAttributes and content a list of #xmlElements|#xmlText|...
%% Have to save namespace nodes. Use of namespace in paths for
%% unique,key and keyref are used after the schema is processed.
S1 = S#xsd_state{targetNamespace=target_namespace(E)},
case is_already_processed(S1#xsd_state.targetNamespace,S1) of
true ->
save_namespace_definition(S1#xsd_state.targetNamespace,S1);
_ ->
S2 = S1,%save_namespace_definition(S1#xsd_state.targetNamespace,S1),
{CM,S3} = traverse_content(E,S2),
save_schema_element(CM,S3),
S3
end.
validate_schema_ph2(S=#xsd_state{derived_types=[]}) ->
S;
validate_schema_ph2(S=#xsd_state{derived_types=DT}) ->
deduce_derived_types(DT,S).
%% traverse_content/2 creates the content model of the schema.
%% content model depends on (1) the type:
%% complex type:
%% sequence, choice, all
%% simple type: no content other than characters
%% (2) minOccurs/maxOccurs attributes.
%% The schema for schemas content model is:
%% schema: ((include | import | redefine | annotation)*,
%% (((simpleType | complexType | group | attributeGroup)
%% | element | attribute | notation), annotation*)*)
%% attribute: (annotation?, simpleType?)
%% element: (annotation?, ((simpleType | complexType)?, (unique |
%% key | keyref)*))
%% complexType: (annotation?, (simpleContent | complexContent |
%% ((group | all | choice | sequence)?,
%% ((attribute | attributeGroup)*,anyAttribute?))))
%% attributeGroup:(annotation?,
%% ((attribute | attributeGroup)*, anyAttribute?))
%% group: (annotation?, (all | choice | sequence)?)
%% all: (annotation?, element*)
%% sequence: (annotation?,
%% (element | group | choice | sequence | any)*)
%% choice: (annotation?, (element | group | choice | sequence |
%% any)*)
%% any: (annotation?) any wellformed xml inside "any"
%% unique: (annotation?, (selector, field+))
%% key: (annotation?, (selector, field+))
%% keyref: (annotation?, (selector, field+))
%% selector: (annotation?)
%% field: (annotation?)
%% notation: (annotation?)
%% annotation: (appinfo | documentation)*
%% appinfo: ({any})*
%% documentation: ({any})*
%% simpleType: (annotation?, (restriction | list | union))
%% restriction: (annotation?, (simpleType?, (minExclusive |
%% minInclusive | maxExclusive | maxInclusive |
%% totalDigits | fractionDigits | length | minLength |
%% maxLength | enumeration | whiteSpace | pattern)*))
%% list: (annotation?, simpleType?)
%% union: (annotation?, simpleType*)
%% include: (annotation?)
%% import: (annotation?)
%% redefine: (annotation | (simpleType | complexType | group |
%% attributeGroup))*
traverse_content(E=#xmlElement{name=Name},S) ->
case local_name(Name) of
schema ->
Content = E#xmlElement.content,
%% S1 = S#xsd_state{targetNamespace=target_namespace(E)},
ThisNS = {"#this#",S#xsd_state.schema_name,
S#xsd_state.targetNamespace},
S2 = S#xsd_state{checked_namespace_nodes=
add_once(ThisNS,S#xsd_state.checked_namespace_nodes)},
S3 = namespace_nodes(E,S2),
S4 = element_form_default(E,S3),
S5 = attribute_form_default(E,S4),
S6 = substitution_default(finalDefault,E,S5),
S7 = substitution_default(blockDefault,E,S6),
traverse_content2(Content,S7,[]);
Err ->
exit({error,{[],?MODULE,{schema_error,Err}}})
end.
traverse_content2([],S,Acc) ->
{reverse(remove_annotation(Acc)),reset_scope(S)};
traverse_content2([El|Els],S,Acc) when is_record(El,xmlElement) ->
%% element declaration: save name, type, scope.
{Object,S2} = element_content(kind(El,S),El,S#xsd_state.scope),%% Object={Kind,Obj}
traverse_content2(Els,S2,[Object|Acc]);
traverse_content2([_T|Els],S,Acc) -> %% xmlText,xmlPI ...
traverse_content2(Els,S,Acc).
target_namespace(E) ->
case get_attribute_value(targetNamespace,E,undefined) of
URI when is_list(URI) ->
list_to_atom(URI);
URI ->
URI
end.
%% namespace_nodes/2 ->
%% NS.
namespace_nodes(#xmlElement{namespace=#xmlNamespace{nodes=NS}},
S=#xsd_state{namespace_nodes=NSN,
global_namespace_nodes=GNSN}) ->
S2 =S#xsd_state{namespace_nodes=foldl(fun add_once/2,NSN,NS)},
S2#xsd_state{global_namespace_nodes=
add_key_once(S#xsd_state.targetNamespace,1,
{S#xsd_state.targetNamespace,NS},
GNSN)}.
attribute_form_default(#xmlElement{attributes=Atts},S)->
Def=form_default(attributeFormDefault,Atts,S),
S#xsd_state{attributeFormDefault=Def}.
element_form_default(#xmlElement{attributes=Atts},S) ->
Def=form_default(elementFormDefault,Atts,S),
S#xsd_state{elementFormDefault=Def}.
form_default(Key,Atts,_S) ->
case keyNsearch(Key,#xmlAttribute.name,Atts,unqualified) of
#xmlAttribute{value=V} when is_list(V) -> list_to_atom(V);
#xmlAttribute{value=V} ->V;
_-> unqualified
end.
substitution_default(Subst = finalDefault,El,S) ->
S#xsd_state{finalDefault = substitution(Subst,El,S)};
substitution_default(Subst = blockDefault,El,S) ->
S#xsd_state{blockDefault = substitution(Subst,El,S)}.
substitution(Subst,El,_S) ->
split_by_whitespace(get_attribute_value(Subst,El,[]),[]).
%% element_content may be one of: annotation, type def(simple or
%% complex), import, unique, key, keyref, attribute def, attribute
%% group, all, group, complexContent, simpleContent, choice, sequence
element_content({attribute,S=#xsd_state{scope=Scope}},Att,Env) ->
case qualify_NCName(Att,S) of
no_name ->
Ref = attribute_ref(Att),
AttRef =
{attribute,get_QName(Ref,Att#xmlElement.namespace, %%QQQ
reset_scope(S))},
{AttRef,add_ref(S,AttRef)};
Name ->
{AttrType,S2} = attribute_type(Att,[Name|Env],S),
S3 = check_cm(attribute,allowed_content(attribute,Env),AttrType,S2),
{Attr,S4} = attribute_properties(Att#xmlElement.attributes,
#schema_attribute{type=AttrType},S3),
Object = {attribute,
Attr#schema_attribute{name=Name,scope=Scope}},
S5 = save_object(Object,S4),
{{attribute,Name},S5}
end;
element_content({element,S},El,Env) ->
%% The type of an element may be a simple or complex type (named
%% or anonymous), a referenced name or member of a substitution group.
case qualify_NCName(El,S) of
no_name ->
Ref = particle_ref(El),
{Occ,S2} = occurrence(El,{1,1},S),
%% 3.3.3 bullet 2.2
S3 = element_forbidden_properties(El,S2),
S4 = element_forbidden_content(El#xmlElement.content,S3),
ElRef =
{element,
{get_QName(Ref,El#xmlElement.namespace,reset_scope(S)),
Occ}},
{ElRef,add_ref(S4,ElRef)};
Name ->
{Type,S2} = element_type(El,[Name|Env],S),
S3 = check_cm(element,allowed_content(element,Env),Type,S2),
Type2 = remove_annotation(Type),
Unique = [X||X={unique,_} <- Type2],
Key = [X||X={K,_} <- Type2,K == key orelse K==keyref],
{Occur,S4} = occurrence(El,{1,1},S3),
{SE,S5} = element_properties(El#xmlElement.attributes,
#schema_element{},El,S4),
CM = remove_attributes([X||X={Y,_}<-Type2,
unique=/=Y,key=/=Y,
keyref=/=Y,annotation=/=Y]),
%% take care of key/keyref later
SE2 = SE#schema_element{name=Name,type=CM,uniqueness=Unique,
key=Key, occurrence=Occur,
scope=S5#xsd_state.scope},
S6 = insert_substitutionGroup(SE2,S5),
S7 = save_object({element,SE2},S6),
{{element,{Name,Occur}},S7}
end;
element_content({complexType,S},CT,Env) ->
%% complex type definition without a name is returned and added to
%% the content model at this level. A complex type may also contain
%% attributes or attribute group references in the end of its content.
%%?debug("complexType content: ~p~nenv: ~p~n",[CT,Env]),
{SCT,S1} = c_t_properties(CT,#schema_complex_type{},S),
{Mixed,S2} = mixed(CT,S1),
Complexity = complexity(CT#xmlElement.content),
{Object,Name,S7} =
case qualify_NCName(CT,S2) of
no_name ->
{CM,S3} = type(CT#xmlElement.content,
in_scope(anonymous,S2),[complexType|Env]),
S4 = check_cm(complexType,allowed_content(complexType,Env),CM,S3),
Name1 = get_QName('_xmerl_no_name_',CT#xmlElement.namespace,S4),
S5 = set_scope(S#xsd_state.scope,S4),
{Content,Attributes}=split_content(remove_annotation(CM)),
SCT2 = base_type(Content,SCT),
CTObj =
{complexType,
SCT2#schema_complex_type{name=Name1,
scope=S5#xsd_state.scope,
attributes=Attributes,
complexity=Complexity,
content=mixify(Mixed,Content)}},
{CTObj,Name1,S5};
Name2 ->
S3 = in_scope(Name2,S2),
S3a = push_circularity_mark({typeDef,Name2},S3),
{CM,S4} = type(CT#xmlElement.content,S3a,
[complexType|Env]),
S4a = pop_circularity_mark({typeDef,Name2},S4),
S5 = check_cm(complexType,allowed_content(complexType,Env),
CM,S4a),
S6 = set_scope(S#xsd_state.scope,S5),
{Content,Attributes}=split_content(remove_annotation(CM)),
SCT2 = base_type(Content,SCT),
{{complexType,
SCT2#schema_complex_type{name=Name2,
scope=S6#xsd_state.scope,
attributes=Attributes,
complexity=Complexity,
content=mixify(Mixed,Content)}},
Name2,S6}
end,
S8 = save_object(Object,S7),
S9 = derived_type(Object,S8),
{{complexType,Name},S9};
element_content({attributeGroup,S},AG,Env) ->
%% an attribute group always have a name or a ref, the content is
%% (annotation?,(attribute | attributGroup)*, anyAttribute?).
case qualify_NCName(AG,S) of
no_name ->
%% an attribute group ref inside complex type def or attr
%% group def ( XSD1:3.6.2).
Ref = attributeGroup_ref(AG),
AGRef =
{attributeGroup,get_QName(Ref,AG#xmlElement.namespace,%%QQQ
reset_scope(S))},
{AGRef,add_ref(S,AGRef)};
Name ->
%% must occur on top level of schema( XSD1:3.6.2). The
%% only thing needed in content are the names of all
%% attributes or referenced attribute groups.
{CM,S2} = type(AG#xmlElement.content,in_scope(Name,S),
[attributeGroup|Env]),
S2_1 = out_scope(Name,S2),
S3 = check_cm(attributeGroup,allowed_content(attributeGroup,Env),CM,S2_1),
S4 = save_object({attributeGroup,
#schema_attribute_group{name=Name,
content=keep_attributes(CM)}},S3),
{{attributeGroup,Name},S4}
end;
element_content({group,S},G,Env) ->
%% a model group associates a name with a content model. It can be
%% a reference or a definition.
%% content is one of all, choice or sequence.
case qualify_NCName(G,S) of
no_name -> % reference.
%% If reference is a recursive ref to a group with the
%% same name as this group points at the redefined valid
%% schema group. See XMLSchema part 1, section 4.2.2
%% "Schema Representation Constraint: Individual Component
%% Redefinition"
Ref = particle_ref(G),
{Occur,S2} = occurrence(G,{1,1},S),
GRef =
{group,
{get_QName(Ref,G#xmlElement.namespace,reset_scope(S2)),%%QQQ
Occur}},
{GRef,add_ref(S2,GRef)};
Name -> % definition, always schema or redefine as parent
{CM,S2} = type(G#xmlElement.content,in_scope(Name,S),[group|Env]),
CM2 = recursive_redefine(Name,CM,S2),
S2_1 = out_scope(Name,S2),
S3 = check_cm(group,allowed_content(group,Env),CM2,S2_1),
S4 = save_object({group,#schema_group{name=Name,
content=remove_annotation(CM2)}},S3),
{{group,Name},S4}
end;
element_content({all,S},All,Env) ->
%% each element occurs 0 or 1 times in any order
%% {all,[{element_name,occurrence}]}
%% CM = content_model(Seq#xmlElement.content,S,[all|Env]),
{Occur,S1} = occurrence(All,{1,1},S),
{CM,S2} = type(All#xmlElement.content,S1,[all|Env]),
S3 = check_cm(all,allowed_content(all,Env),CM,S2),
{{all,{[X||X = {element,_} <- CM],Occur}},S3};
element_content({sequence,S},Seq,Env) ->
%% {sequence,[{element_name,occurrence}]}
%% CM = content_model(Seq#xmlElement.content,S,[sequence|Env]),
{Occur,S1} = occurrence(Seq,{1,1},S),
{CM,S2} = type(Seq#xmlElement.content,S1,[sequence|Env]),
S3 = check_cm(sequence,allowed_content(sequence,Env),CM,S2),
{{sequence,{remove_annotation(CM),Occur}},S3};
element_content({choice,S},Choice,Env) ->
%% allowed content: (annotation?,
%% (element | group | choice | sequence | any)*)
%% returns: {choice,[element_name]}
%% CM = content_model(Choice#xmlElement.content,S,[choice|Env]),
{Occur,S1} = occurrence(Choice,{1,1},S),
{CM,S2} = type(Choice#xmlElement.content,S1,[choice|Env]),
S3 = check_cm(choice,allowed_content(choice,Env),CM,S2),
{{choice,{remove_annotation(CM),Occur}},S3};
element_content({any,S},Any,_Env) ->
{Occur,S1} = occurrence(Any,{1,1},S),
NameSpace = wildcard_namespace(Any,S1),
PC = processor_contents(Any),
?debug("element_content, any: Any content:~p~n",[Any#xmlElement.content]),
Pred = fun(E=#xmlElement{}) -> case kind(E) of
annotation -> false;
_ -> true
end;
(_) ->
false
end,
S2 = case filter(Pred,Any#xmlElement.content) of
[] -> S1;
Err -> %% report error
acc_errs(S1,{error_path(Any,Any#xmlElement.name),?MODULE,
{unexpected_content_in_any,Err}})
end,
{{any,{NameSpace,Occur,PC}},S2};
element_content({IDC,S},El,Env)
when IDC==unique;IDC==key;IDC==keyref->
QName = qualify_NCName(El,reset_scope(S)),
Ref = keyrefer(IDC,El,S),
{SelField,S2} = type(El#xmlElement.content,S,[IDC|Env]),
case {[X||X={selector,_} <- SelField],[X||X={field,_} <- SelField]} of
{[Sel],Fields=[_H|_T]} ->
IDConstr = #id_constraint{category=IDC,name=QName,refer=Ref,
selector=Sel,fields=Fields},
S3=save_idc(IDC,IDConstr,S2),
{{IDC,IDConstr},S3};
Err ->
S3 = acc_errs(S2,{error_path(El,El#xmlElement.name),?MODULE,
{erroneous_content_in_identity_constraint,IDC,Err}}),
{{IDC,[]},S3}
end;
element_content({selector,S},Sel,_Env) ->
case get_attribute_value(xpath,Sel,error) of
error ->
S2 = acc_errs(S,{error_path(Sel,Sel#xmlElement.name),?MODULE,
{missing_xpath_attribute,selector}}),
{{selector,[]},S2};
XPath ->
{{selector,XPath},S}
end;
element_content({field,S},F,_Env) ->
case get_attribute_value(xpath,F,error) of
error ->
S2 = acc_errs(S,{error_path(F,F#xmlElement.name),?MODULE,
{missing_xpath_attribute,field}}),
{{field,[]},S2};
XPath ->
{{field,XPath},S}
end;
element_content({notation,S},_N,_Env) ->
{{notation,[]},S};
element_content({annotation,S},_Ann,_Env) ->
{{annotation,[]},S};
element_content({appinfo,S},_AI,_Env) ->
{{appinfo,[]},S};
element_content({documentation,S},_D,_Env) ->
{{documentation,[]},S};
element_content({simpleType,S},ST,Env) ->
Name = case qualify_NCName(ST,S) of
no_name ->
get_QName('_xmerl_no_name_',ST#xmlElement.namespace,
in_scope('_xmerl_no_name_',S));%%---
QName ->
QName
end,
{Type,S2} = type(ST#xmlElement.content,
push_circularity_mark({typeDef,Name},in_scope(Name,S)),
[simpleType|Env]),
S2_1 = pop_circularity_mark({typeDef,Name},S2),
S3 = set_scope(S#xsd_state.scope,S2_1),
S4 = check_cm(simpleType,allowed_content(simpleType,Env),Type,S3),
{BaseType,Facets} = facets(Type,S4),
Variety = variety(Type),
Final = simpleType_final(ST,S4),
Object = {simpleType,#schema_simple_type{name=Name,
base_type=BaseType,
final=Final,
facets=Facets,
variety=Variety,
content=remove_annotation(Type),
scope=S4#xsd_state.scope}},
S5 = save_object(Object,S4),
S6 = derived_type(Object,S5),
{{simpleType,Name},S6};
element_content({restriction,S},R,Env) ->
%% If complexContent, all element definitions of base type must be
%% repeated. However, attributes are inherited.
%% possible parents are simpleType or complexType (grand parent)
%% If parent is simpleType the base type is either the attribute
%% base (resolved by base_type/1) or the type defined in content.
{CM,S2} = type(R#xmlElement.content,S,[restriction|Env]),
S3 = check_cm(restriction,allowed_content(restriction,Env),CM,S2),
{BaseTypeName,CM2,S4} = restriction_base_type(R,CM,S3), %% a QName
%% S5 = add_circularity_mark(BaseTypeName,S4),
BaseTypeType = base_type_type(Env),
{{restriction,{BaseTypeName,remove_annotation(CM2)}},
add_ref(S4,{BaseTypeType,BaseTypeName})}; %% Does not return name but content model
element_content({list,S=#xsd_state{scope=Scope}},L,Env) ->
{Type,S2} = list_type(L,S,[list|Env]),
S3 = check_cm(list,allowed_content(list,Scope),Type,S2),
{{list,remove_annotation(Type)},S3};
element_content({union,S=#xsd_state{scope=Scope}},U,Env) ->
{Types,S2} = union_types(U,S,[union|Env]),
S3 = check_cm(union,allowed_content(union,Scope),Types,S2),
{{union,Types},S3};
element_content({include,S=#xsd_state{schema_name=ThisSchema,
targetNamespace=TNS}},I,_Env) ->
S2 = process_external_schema_once(I,S#xsd_state.targetNamespace,S),
{{include,[]},S2#xsd_state{schema_name=ThisSchema,targetNamespace=TNS}};
element_content({import,S=#xsd_state{schema_name=ThisSchema,
targetNamespace=ThisNameS}},I,_Env) ->
%% import unlike include and redefine may include definitions from
%% other namespaces than the target namespace of the including
%% schema.
%% namespace and schemaLocation
Namespace =
case get_attribute_value(namespace,I,undefined) of
L when is_list(L) ->
list_to_atom(L);
A -> A
end,
%% If Namespace is absent, then the import allows unqualified
%% reference to components with no target namespace.
SchemaLocation = get_attribute_value(schemaLocation,I,absent),
%% If SchemaLocation is absent, the identification of that schema
%% is leaved to the instance, application or user, via the
%% mechanisms described §4.3 in XML Schema Part 1.
S2 = process_external_schema_once(SchemaLocation,Namespace,S),
{{import,[]},S2#xsd_state{schema_name=ThisSchema,
targetNamespace=ThisNameS}};
element_content({redefine,S=#xsd_state{schema_name=ThisSchema}},RD,Env) ->
%% Must be a child of "schema" element
%% redefine of simple and complex types, groups and attribute
%% groups obtained from external files.
%% Brings in all definitions of external schema and redefines one.
%% External schema must be in same namespace as current schema or
%% no namespace.
S2 = process_external_schema_once(RD,S#xsd_state.targetNamespace,
S#xsd_state{errors=[]}),
case S2#xsd_state.errors of
[] ->
%% RedefSource = S2#xsd_state.schema_name,
S3 = S2#xsd_state{schema_name=ThisSchema,
%% global_element_source=add_once({ThisSchema,RedefSource},GES),
errors=S#xsd_state.errors},
{CM,S4} = type(RD#xmlElement.content,
S3#xsd_state{redefine=true},[redefine|Env]),
S5 = S4#xsd_state{redefine=false},
S6 = check_cm(redefine,allowed_content(redefine,Env),CM,S5),
S7 = redefine(CM,S6),
{{redefine,[]},S7};
Errs ->
S3 = S2#xsd_state{schema_name=ThisSchema,
errors=Errs++S#xsd_state.errors},
{{redefine,[]},S3}
end;
element_content({anyAttribute,S},AA,_Env) ->
%% has attributes processContents = (lax | skip | strict) : strict
%% namespace = ((##any | ##other) |
%% List of (anyURI | (##targetNamespace | ##local)) ) : ##any
NameSpace = wildcard_namespace(AA,S),
PC = processor_contents(AA),
Pred = fun(E=#xmlElement{}) -> case kind(E) of
annotation -> false;
_ -> true
end;
(_) -> false
end,
S2 =
case filter(Pred,AA#xmlElement.content) of
[] -> S;
Err -> %% report error
acc_errs(S,{error_path(AA,AA#xmlElement.name),?MODULE,
{content_in_anyAttribute,Err}})
end,
{{anyAttribute,{NameSpace,PC}},S2};
element_content({simpleContent,S},SC,Env) ->
%% only as child of complexType.
%% allowed content: (annotation?, (restriction | extension))
S2 = pre_check_cm(simpleContent,SC#xmlElement.content,mk_name(S#xsd_state.scope),S),
case filter(fun(X=#xmlElement{}) ->
case kind(X) of
restriction -> true;
extension -> true;
_ -> false
end;
(_) -> false
end,
SC#xmlElement.content) of
[E] ->
element_content(kind(E,S2),E,[simpleContent|Env]);
Err ->
{[],acc_errs(S2,{error_path(SC,SC#xmlElement.name),?MODULE,
{content_in_simpleContent,Err}})}
end;
element_content({complexContent,S},CC,Env) ->
S2 = pre_check_cm(complexContent,CC#xmlElement.content,
mk_name(S#xsd_state.scope),S),
%% the mixed attribute was fetched in the complexType element that
%% held this complexContent
case filter(fun(X=#xmlElement{}) -> case kind(X) of
restriction -> true;
extension -> true;
_ -> false
end;
(_) -> false
end,CC#xmlElement.content) of
[E] ->
element_content(kind(E,S2),E,[complexContent|Env]);
Err ->
{[],acc_errs(S2,{error_path(CC,CC#xmlElement.name),?MODULE,
{complexContent_content_failure,Err}})}
end;
element_content({extension,S},Ext,Env) ->
%% may be used in both simple and complex content with different
%% content allowed.
%% this should be returned and checked for allowed content in
%% parent, but we don't know if base type is a forward reference.
BaseType = base_type(Ext),
{CM,S2} = type(Ext#xmlElement.content,S,[extension|Env]),
S3 = check_cm(extension,allowed_content(extension,S#xsd_state.scope),CM,S2),
BaseTypeName = get_QName(BaseType,Ext#xmlElement.namespace,reset_scope(S)),%%QQQ
BaseTypeType = base_type_type(Env),
{{extension,{BaseTypeName,CM}},add_ref(S3,{BaseTypeType,BaseTypeName})};