1 % (c) 2016-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html
4
5 :- module(xml2b,[convert_xml_to_b/4, convert_json_to_b/3]).
6
7 :- use_module(probsrc(module_information),[module_info/2]).
8 :- module_info(group,external_functions).
9 :- module_info(description,'This module transforms XML into a B representation.').
10
11 :- use_module(probsrc(xml_prob),[xml_parse/4]).
12 %:- use_module(library(xml),[xml_parse/3]).
13 :- use_module(library(lists)).
14 :- use_module(probsrc(custom_explicit_sets),[convert_to_avl/2, construct_singleton_avl_set/2]).
15 :- use_module(probsrc(error_manager)).
16 :- use_module(probsrc(debug)).
17 :- use_module(probsrc(tools_strings),[ajoin/2]).
18
19 % type of generated XML elements:
20 /* struct(
21 recId: NATURAL1,
22 pId:NATURAL,
23 element:STRING,
24 attributes: STRING +-> STRING,
25 meta: STRING +-> STRING
26 )
27 */
28
29 % convert a code list to a B sequence/set of records
30 % Context is file name or string and is used for error messages only
31 convert_xml_to_b(Codes,BContent,Context,Span) :-
32 reset_counter(xml2b_current_line),
33 set_counter(xml2b_current_line,1),
34 peel_and_count_newlines(Codes,PeeledCodes),
35 (debug_mode(off) -> true
36 ; get_counter(xml2b_current_line,InitialLineNr),
37 format('XML starting at line: ~w of ~w~n',[InitialLineNr,Context])),
38 %statistics(walltime,[W1,_]),
39 xml_parse(PeeledCodes,xml(_Atts,Content),[format(false)],Span), % format(false) means we also see all newlines
40 %statistics(walltime,[W2,_]), W is W2-W1, formatsilent('% Walltime ~w ms to parse XML using Prolog library~n',[W]),
41 % xml_prob:xml_pp(xml(_Atts,Content)),nl,
42 % xml_parse(Codes2,xml(_Atts,Content),[]), format('XML:~n~s~n',[Codes2]),
43 %print(Content),nl,nl,
44 !,
45 (convert_xml_content_to_b(Content,0,1,_,Conversion,[]) -> BContent = Conversion
46 ; add_error(convert_xml_to_b,'Converting XML content to B failed:',Content,Span), % probably an internal error
47 fail
48 ).
49 convert_xml_to_b(_,_,Context,Span) :-
50 add_error(convert_xml_to_b,'XML Parsing failed, ensure that XML is valid in:',Context,Span),fail.
51
52
53 convert_xml_content_to_b([],_ParentId,NextId,OutId) --> {OutId=NextId}.
54 convert_xml_content_to_b([H|T],ParentId,NextId,OutId) -->
55 convert_xml_element(H,ParentId,NextId,Id2),
56 convert_xml_content_to_b(T,ParentId,Id2,OutId).
57
58 % TO DO: do we need to parse namespaces...
59 % TO DO: store meta-information
60 % TO DO: adapt line numbers when newlines inside initial tag: <?xml version="1.0" encoding="ASCII"?>
61 % TO DO: deal with new lines inside tags <Data version= "03.04"> : Prolog library hides those newlines !
62
63 convert_xml_element(Element, ParentId,NextId,OutId) -->
64 % {get_counter(xml2b_current_line,CurNr),nl,print(el(CurNr,Element)),nl},
65 {xml_element(Element,Tag,Attributes,Content,LineNr)},
66 !,
67 [(int(NextId),
68 rec([ % note: fields have to be in order
69 field(attributes,BAttributes), % partial function of Attributes
70 field(element,string(Tag)),
71 field(meta,MetaAttributes), % such as xmlLineNumber
72 field(pId,int(ParentId)), % id of the parent XML record
73 field(recId,int(NextId)) % id of the XML element/record
74 ])
75 )],
76 {Id2 is NextId+1,
77 number_codes(LineNr,LCC), atom_codes(LineNrAtom,LCC),
78 construct_singleton_avl_set((string(xmlLineNumber),string(LineNrAtom)),MetaAttributes),
79 l_convert_xml_attributes(Attributes,BAttributesList),
80 convert_to_avl(BAttributesList,BAttributes)
81 },
82 convert_xml_content_to_b(Content,NextId,Id2,OutId).
83 convert_xml_element(namespace( URL, NS, Element), ParentId,NextId,OutId) --> !, % what should we do with the namespace?
84 {(URL='', NS=[] -> true
85 ; get_counter(xml2b_current_line,LineNr),
86 debug_format(19,'Ignoring XML namespace "~s" annotation on line ~w with URL: ~w~n',[NS,LineNr,URL]))},
87 convert_xml_element(Element, ParentId,NextId,OutId).
88 convert_xml_element(pcdata(_Codes),_,Id,Id) --> !. % should only happen when Codes consists solely of newlines
89 % no need to count_newlines; already done below in xml_element before C1 \= []
90 convert_xml_element(comment(Codes),_,Id,Id) --> !,{count_newlines(Codes)}.
91 convert_xml_element(instructions(Name, Chars),_,Id,Id) --> !,
92 {get_counter(xml2b_current_line,LineNr),
93 debug_format(19,'Ignoring XML instructions annotation on line ~w: ~w : ~s~n',[LineNr,Name,Chars])}.
94 convert_xml_element(doctype(Tag, DoctypeId),_,Id,Id) --> !,
95 {get_counter(xml2b_current_line,LineNr),
96 debug_format(19,'Ignoring XML doctype annotation on line ~w: ~w : ~w~n',[LineNr,Tag,DoctypeId])}.
97 convert_xml_element(cdata(Codes),ParentId,Id,OutId) --> !,
98 % TO DO: tab expansion? see http://binding-time.co.uk/wiki/index.php/Parsing_XML_with_Prolog
99 convert_xml_element(pcdata(Codes),ParentId,Id,OutId).
100 convert_xml_element(El,_,Id,Id) -->
101 {get_counter(xml2b_current_line,LineNr),
102 ajoin(['Ignoring unknown XML element on line ',LineNr,':'],Msg),
103 add_warning(convert_xml_to_b,Msg,El)}.
104
105
106 xml_element(element(Tag,XAttributes,Content),Tag,Attributes,Content,LineNr) :-
107 get_counter(xml2b_current_line,CurLineNr),
108 LineNr = CurLineNr, % the line where the start tag begins
109 (select('='('$attribute_linefeeds',LF),XAttributes,Rest)
110 -> Attributes = Rest, % LF newlines inside the start tag; content starts LF lines later
111 NewLineNr is CurLineNr+LF,
112 set_counter(xml2b_current_line,NewLineNr)
113 ; Attributes=XAttributes).
114 xml_element(pcdata(Codes),'CText',['='(text,NewCodes)],[],LineNr) :-
115 peel_and_count_newlines(Codes,C1),
116 C1 \= [],
117 get_counter(xml2b_current_line,LineNr),
118 count_newlines_and_trim(C1,NewCodes).
119
120
121 l_convert_xml_attributes([],[]).
122 l_convert_xml_attributes([H|T],[CH|CT]) :- convert_xml_attributes(H,CH),
123 l_convert_xml_attributes(T,CT).
124
125 convert_xml_attributes('='(Attr,Codes),(string(Attr),string(Atom))) :- !,atom_codes(Atom,Codes).
126 convert_xml_attributes(A,(string(error),string(A))) :- add_warning(convert_xml_to_b,'Unknown XML attribute: ',A).
127
128
129 :- use_module(extension('counter/counter'),
130 [counter_init/0, new_counter/1, get_counter/2, inc_counter/1, reset_counter/1, set_counter/2]).
131
132 count_newlines([]) :- !.
133 count_newlines(HT) :- newline(HT,T),!, inc_counter(xml2b_current_line), count_newlines(T).
134 count_newlines([_|T]) :- count_newlines(T).
135
136 % peel leading newlines
137 peel_and_count_newlines([],Res) :- !, Res=[].
138 peel_and_count_newlines([H|T],Res) :- (whitespace(H) -> peel_and_count_newlines(T,Res)
139 ; H=10 -> inc_counter(xml2b_current_line), peel_and_count_newlines(T,Res)
140 ; H=13 -> inc_counter(xml2b_current_line),
141 (T=[10|TX]
142 -> peel_and_count_newlines(TX,Res)
143 ; peel_and_count_newlines(T,Res))
144 ; Res = [H|T]).
145 %peel_and_count_newlines(R,R).
146
147 % count new lines and trim trailing whitespace (newlines, spaces, tabs); inner newlines become 10
148 count_newlines_and_trim([],Res) :- !, Res=[].
149 count_newlines_and_trim(HT,Res) :- newline(HT,R),!, inc_counter(xml2b_current_line),
150 count_newlines_and_trim3(R,[10],Res).
151 count_newlines_and_trim([H|T],Res) :- whitespace(H),!,
152 count_newlines_and_trim3(T,[H],Res).
153 count_newlines_and_trim([H|T],[H|TRes]) :-
154 count_newlines_and_trim(T,TRes).
155
156 count_newlines_and_trim3([],_,Res) :- !, Res=[]. % ignore accumulator
157 count_newlines_and_trim3(HT,Acc,Res) :- newline(HT,R),!, inc_counter(xml2b_current_line),
158 count_newlines_and_trim3(R,[10|Acc],Res).
159 count_newlines_and_trim3([H|T],Acc,Res) :- whitespace(H),!,
160 count_newlines_and_trim3(T,[H|Acc],Res).
161 count_newlines_and_trim3([H|T],Acc,Res) :-
162 revacc(Acc,[H|TRes],Res), count_newlines_and_trim(T,TRes).
163
164 revacc([],Acc,Acc).
165 revacc([H|T],Acc,Res) :- revacc(T,[H|Acc],Res).
166
167 newline([H|T],R) :- (H=10 -> R=T ; H=13 -> (T=[10|TX] -> R=TX ; R=T)).
168 % TO DO: should we check if we are on Windows ?
169
170 whitespace(9). % tab
171 whitespace(32).
172
173 xml2b_startup :- % call once at startup to ensure all counters exist
174 counter_init,
175 new_counter(xml2b_current_line).
176
177 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
178 :- register_event_listener(startup_prob,xml2b_startup,
179 'Initialise xml2b Counters.').
180
181 % ------------------------------
182 % convert a format received by json_parser:json_parse_file into the same format as READ_XML
183
184 convert_json_to_b(Json,BContent,Span) :- !,
185 (convert_json_element(Json,0,1,_,1,Span,Conversion,[])
186 -> BContent=Conversion
187 ; add_error(convert_json_to_b,'Converting JSON content to B failed:',Json,Span), % probably an internal error
188 fail
189 ).
190
191 convert_json_content_to_b([],_ParentId,NextId,OutId,_,_Span) --> {OutId=NextId}.
192 convert_json_content_to_b([H|T],ParentId,NextId,OutId,LineNr,Span) -->
193 convert_json_element(H,ParentId,NextId,Id2,LineNr,Span),
194 convert_json_content_to_b(T,ParentId,Id2,OutId,LineNr,Span).
195
196 convert_json_element(Element,ParentId,NextId,OutId,ParentLineNr,Span) -->
197 {json_element(Element,Tag,BAttributesList,Content,LineNr)},
198 !,
199 {var(LineNr) -> LineNr=ParentLineNr ; true}, % values have no position info: use the line of the parent
200 [(int(NextId),
201 rec([ % note: fields have to be in order
202 field(attributes,BAttributes), % partial function of Attributes
203 field(element,string(Tag)),
204 field(meta,MetaAttributes), % such as xmlLineNumber
205 field(pId,int(ParentId)), % id of the parent XML record
206 field(recId,int(NextId)) % id of the XML element/record
207 ])
208 )],
209 {Id2 is NextId+1,
210 number_codes(LineNr,LCC), atom_codes(LineNrAtom,LCC),
211 convert_to_avl([(string(xmlLineNumber),string(LineNrAtom))],MetaAttributes),
212 convert_to_avl(BAttributesList,BAttributes)
213 },
214 convert_json_content_to_b(Content,NextId,Id2,OutId,LineNr,Span).
215 convert_json_element(El,_,Id,Id,LineNr,Span) -->
216 {ajoin(['Cannot translate JSON element at line ',LineNr,' to B:'],Msg),
217 add_error(convert_json_to_b,Msg,El,Span)}.
218
219 % for all elements except attributes the line number is unknown (the parent's line number is used)
220 json_element(@(null),null,[],[],_) :- !.
221 json_element(@(true),boolean,[(string(value),string(true))],[],_) :- !.
222 json_element(@(false),boolean,[(string(value),string(false))],[],_) :- !.
223 json_element(number(Number),number,[(string(value),string(Atom))],[],_) :- !,
224 number_codes(Number,Codes), atom_codes(Atom,Codes).
225 json_element(string(String),string,[(string(value),string(String))],[],_) :- !.
226 json_element(json(Object),object,[],Object,_) :- !.
227 json_element(array(Array),array,[],Array,_) :- !.
228 json_element('='(Key,Value,Pos),attribute,[(string(key),string(Key))],[Value],LineNr) :- !, get_line_nr(Pos,LineNr).
229
230 get_line_nr(L-_,L) :- !.
231 get_line_nr(E,0) :- debug_format(19,'No position info for JSON attribute: ~w~n',[E]).