1 % (c) 2025-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(source_indenter,[indent_b_file/2, indent_b_file/3,
6 indent_b_file_to_codes/2, indent_b_file_to_codes/3,
7 reformat_b_file_to_codes/2]).
8
9
10 :- use_module(probsrc(module_information),[module_info/2]).
11 :- module_info(group,misc).
12 :- module_info(description,'This module can indent B source files using a lexing approach.').
13
14 % the idea is to keep track of keywords relevant of increase/decrease of indentation level
15 % it basically requires correct lexing of these keywords, and does not require parsing
16 % it can thus deal with comments anywhere in the source code and also with files that cannot be parsed
17 % it, however, currently does not check that opening/closing tags match
18
19 % options for:
20 % - indent_spaces/Nr: number of whitespaces per indentation :
21 % - insert_new_lines_before_keywords: whether to automatically insert newlines before keywords like ELSIF, ...
22 % - insert_new_lines_after_keywords: whether to automatically insert newlines after keywords like ELSIF, ...
23 % - whether to add current indent level inside comments or not
24 % TODO: parse special unicode identifiers, ... (ideally we would conform exactly to BLexer.java)
25
26 :- use_module(library(codesio), [with_output_to_codes/4]).
27 :- use_module(probsrc(error_manager),[add_internal_error/2]).
28
29 reformat_b_file_to_codes(File,Codes) :-
30 indent_b_file_to_codes(File,Codes,[insert_new_lines_before_keywords,insert_new_lines_after_keywords]).
31 indent_b_file_to_codes(File,Codes) :-
32 indent_b_file_to_codes(File,Codes,[]).
33 indent_b_file_to_codes(File,Codes,Opts) :-
34 with_output_to_codes(
35 indent_b_file(File,OutStream,Opts),
36 OutStream,
37 Codes, []).
38
39 indent_b_file(File,OutStream) :-
40 indent_b_file(File,OutStream,
41 [] %
42 % [insert_new_lines_after_keywords, insert_new_lines_before_keywords, half_indent_elsif, indent_spaces/8]
43 ).
44
45 indent_b_file(File,OutStream,Opts) :-
46 open(File,read,Stream,[encoding(utf8)]),
47 init_env(OutStream,Opts,Env),
48 call_cleanup(process_file(Stream,Env), close(Stream)).
49
50 process_file(Stream,Env) :-
51 read_line(Stream,Codes),
52 (Codes = end_of_file -> true
53 ; % format('>~s[~w]~n',[Codes,Env]),
54 (process_line(Env,Env1,Codes,[]) -> true
55 ; add_internal_error('Could not indent line: ',Codes), % should not happen
56 Env1=Env, output_codes(Env,Codes)),
57 output_new_line(Env1,Env2),
58 process_file(Stream,Env2)
59 ).
60
61
62 ?identifier(ID) --> [X], {is_alpha(X)}, id_aux(T), {atom_codes(ID,[X|T])}.
63
64 id_aux([0'_|T]) --> "_",!, id_aux(T).
65 id_aux([X|T]) --> [X], {is_numerical(X)},!, id_aux(T).
66 ?id_aux([X|T]) --> [X], {is_alpha(X)},!, id_aux(T).
67 id_aux([]) --> "".
68
69
70 is_numerical(Code) :- Code >= 48, Code =< 57. % 0-9
71
72 is_alpha(Code) :- Code >= 65, Code =< 90. % A-Z
73 is_alpha(Code) :- Code >= 97, Code =< 122. % a-z
74 is_alpha(Code) :- Code >= 0xC0, Code =< 0x24F, Code \= 0xD7, Code \= 0xF7. % Latin letters with accents (not times, divide)
75 is_alpha(Code) :- Code >= 0x391, Code =< 0x3C9, Code \= 0x3BB. % Greek letters, except lambda (used as operator)
76
77 process_line(env(I,Stream,Open,Opts),ResEnv) -->
78 {Open = open_special_token(Kind,Close)},!, % continue processing open special token
79 ({Kind = comment}
80 -> skip_ws, % replace leading whitespace by current indentation, so that indenting is idempotent
81 ([0'*] -> {output_indent(env(I,Stream,Open,Opts)), output_codes(env(I,Stream,Open,Opts)," *")}
82 ; {output_indent(env(I,Stream,Open,Opts)), output_codes(env(I,Stream,Open,Opts)," ")}
83 )
84 ; []), % multi-line strings are kept unchanged
85 process_special_token(Kind,Close,env(I,Stream,no_open_special_token,Opts),ResEnv).
86 process_line(Env,ResEnv) --> process_line2(Env,ResEnv).
87
88
89 ?process_line2(Env,ResEnv) --> ws, !, process_line2(Env,ResEnv). % ignore any leading ws on a line
90 ?process_line2(Env,ResEnv) --> identifier(ID),
91 ? {is_b_keyword(ID,section), \+ is_indent_relevant_keyword(ID,_)},!, % No indent
92 {output_atom(Env,ID),process_id(ID,Env,Env1)},
93 process_line_rest(Env1,ResEnv).
94 ?process_line2(Env,ResEnv) --> identifier(ID),
95 {is_indent_relevant_keyword(ID,Delta), Delta=<0},!,
96 % END, decrement indent immediately; ELSIF decrement for this line only
97 {process_id(ID,Env,Env1),
98 output_indent_delta(Delta,Env1),
99 output_atom(Env1,ID)},
100 process_line_after_id(ID,Env1,ResEnv).
101 process_line2(Env,ResEnv) --> [C],
102 {is_ident_relevant_code(C,Delta), Delta =< 0},!, % open or closing brackets
103 {update_indent(Env,Delta,Env1),
104 output_indent_delta(Delta,Env1), output_code(Env1,C)},
105 process_line_rest(Env1,ResEnv).
106 %process_line2(Env,ResEnv,T,T) :- T \= [_|_], !, write(xx(T)),ResEnv=Env. % finished
107 process_line2(Env,ResEnv) --> {output_indent(Env)}, process_line_rest(Env,ResEnv).
108
109 % continue processing line after an ID; optionally insert newlines
110 process_line_after_id(ID,Env,Res) -->
111 ({is_indent_relevant_keyword(ID,0),
112 option_set(insert_new_lines_after_keywords,Env)},
113 \+ at_end_of_line
114 -> process_new_line(Env,Res)
115 ; process_line_rest(Env,Res)
116 ).
117
118 ?skip_ws --> ws,!, skip_ws.
119 skip_ws --> "".
120
121 ?at_end_of_line --> ws,!, at_end_of_line.
122 at_end_of_line --> "".
123
124
125 % output indent for a indent_relevant_keyword with given Delta value
126 output_indent_delta(Delta,Env1) :- Delta=0,!, % things like ELSIF, ...
127 dec_indent(Env1,Env2),% move ELSIF one to the left
128 output_indent(Env2).
129 output_indent_delta(_,Env) :- output_indent(Env).
130
131 ?process_line_rest(Env,Res) --> identifier(ID),!,
132 {(is_indent_relevant_keyword(ID,0),
133 ? option_set(insert_new_lines_before_keywords,Env)
134 -> output_new_line(Env,Env1),output_indent_delta(0,Env1) ; Env1=Env),
135 output_atom(Env1,ID),
136 process_id(ID,Env1,Env2)
137 },
138 process_line_after_id(ID,Env2,Res).
139 process_line_rest(Env,Res) --> new_line,!, process_new_line(Env,Res).
140 process_line_rest(Env,Res) --> line_comment,!, {output_codes(Env,"//")}, process_line_comment(Env,Res).
141 ?process_line_rest(Env,Res) --> open_special_token(Kind,Open,Close),!,
142 {output_codes(Env,Open)}, process_special_token(Kind,Close,Env,Res).
143 ?process_line_rest(Env,Res) --> ws, skip_ws, % drop whitespace before a keyword which is moved to a new line
144 ? {option_set(insert_new_lines_before_keywords,Env)},
145 ? peek_new_line_keyword,!,
146 process_line_rest(Env,Res).
147 ?process_line_rest(In,Out) --> get_regular_token(Ts), !, {output_codes(In,Ts)}, process_line_rest(In,Out).
148 process_line_rest(In,Out) --> [C], {is_ident_relevant_code(C,Delta)},!,
149 {output_code(In,C),update_indent(In,Delta,In2)}, process_line_rest(In2,Out).
150 process_line_rest(In,Out) --> [C], !, {output_code(In,C)}, process_line_rest(In,Out).
151 process_line_rest(Env,Env) --> "".
152 % TODO: detect other comments, strings
153 % TODO: possibly insert new-lines for sections or things like ELSIF
154
155 % look ahead (without consuming) for a keyword like THEN, ELSE which will be moved to a new line
156 ?peek_new_line_keyword(S,S) :- identifier(ID,S,_), is_indent_relevant_keyword(ID,0).
157
158 process_new_line(Env,Env2) --> {output_new_line(Env,Env1)}, process_line2(Env1,Env2).
159
160 process_line_comment(Env,Env2) --> new_line,!, process_new_line(Env,Env2).
161 process_line_comment(Env,Env2) --> [X],!, {output_code(Env,X)}, process_line_comment(Env,Env2).
162 process_line_comment(Env,Env) --> "".
163
164 % TODO: process special encodings \", ....
165 process_special_token(string,Close,Env,OutEnv) --> special_string_encoding(Env),!,
166 process_special_token(string,Close,Env,OutEnv).
167 process_special_token(_Kind,Close,Env,OutEnv) --> Close,!, {output_codes(Env,Close)},
168 process_line_rest(Env,OutEnv).
169 process_special_token(Kind,Close,In,Out) --> [C], !, {output_code(In,C)}, process_special_token(Kind,Close,In,Out).
170 process_special_token(Kind,Close,Env,OutEnv) --> "", {register_open_special_token(Env,Kind,Close,OutEnv)}.
171
172 special_string_encoding(Env) --> "\\", [X], % TODO: check exactly which encodings are processed
173 {output_codes(Env,"\\"),output_code(Env,X)}.
174
175 ws --> " "; "\t".
176 new_line --> "\n". %,{inc_line_nr}.
177 line_comment --> "//".
178
179 % open special token whose contents should be ignored for indentation
180 open_special_token(comment,"/*","*/") --> "/*".
181 open_special_token(string,"\"","\"") --> "\"".
182 open_special_token(string,"'''","'''") --> "'''".
183 open_special_token(string,"```","```") --> "```".
184 open_special_token(identifier,"`","`") --> "`". % multi-line allowed??
185
186 % recognise some tokes, in particular those that contain indent relevant tokens like vertical bar |
187 get_regular_token("|->") --> "|->". % maplet
188 get_regular_token("||") --> "||".
189 get_regular_token("|>>") --> "|>>".
190 get_regular_token("|>") --> "|>".
191 get_regular_token("<<|") --> "<<|".
192 get_regular_token("<|") --> "<|".
193 get_regular_token("/|\\") --> "/|\\".
194 get_regular_token("\\|/") --> "\\|/".
195 get_regular_token("..") --> "..".
196 % below not really necessary?
197 get_regular_token("\\/") --> "\\/".
198 get_regular_token("/\\") --> "/\\".
199
200 % use a fact to keep track of line numbers
201 %:- dynamic cur_line/1.
202 %reset_line_nr :- retractall(cur_line(_)), assertz(cur_line(1)).
203 %inc_line_nr :- cur_line(N), !, retractall(cur_line(_)), N1 is N+1, assertz(cur_line(N1)).
204 %inc_line_nr.
205 %:- dynamic linecount/1.
206 %inc_linecount(X) :- retract(linecount(X)), !, X1 is X+1, assert(linecount(X1)).
207 %inc_linecount(0) :- assert(linecount(1)).
208
209
210 init_env(OutStream,Opts,env(0,OutStream,no_open_special_token,Opts)).
211
212 ?option_set(Option,env(_,_,_,Opts)) :- member(Option,Opts).
213
214 register_open_special_token(env(C,Stream,_,Opts),Kind,CloseTag,
215 env(C,Stream,open_special_token(Kind,CloseTag),Opts)).
216
217 % output preds
218 output_indent(env(Nr,Str,K,Opts)) :- Nr>0, !, write(Str,' '), N1 is Nr-1, output_indent(env(N1,Str,K,Opts)).
219 output_indent(_).
220
221
222 output_new_line(env(E,Stream,K,Opts),env(E,Stream,K,Opts)) :-
223 %inc_linecount(LC), format('//[~w - line ~w]',[E,LC]), % for debugging
224 nl(Stream).
225
226 output_code(env(_,Stream,_,_),C) :- put_code(Stream,C).
227 output_codes(env(_,Stream,_,_),Cs) :- format(Stream,'~s',[Cs]).
228 output_atom(env(_,Stream,_,_),C) :- format(Stream,'~w',[C]).
229
230
231 :- use_module(probsrc(tools_matching),[is_b_keyword/2]).
232
233 process_id(ID,env(C,S,K,Opts),env(NC,S,K,Opts)) :- is_indent_relevant_keyword(ID,Delta),!,
234 get_indent_spaces(Opts,Nr), NC is C+Nr*Delta. % format('~w->~w ',[C,NC]).
235 ?process_id(ID,env(_,S,K,Opts),env(NC,S,K,Opts)) :- is_b_keyword(ID,section),!,
236 get_indent_spaces(Opts,NC). % reset to beginning of line
237 process_id(_ID,C,C). % :- format('?~w?',[_ID]).
238
239 get_indent_spaces(Opts,Nr) :- (member(indent_spaces/N,Opts) -> Nr=N ; Nr=4).
240
241 % dec indent for one line for ELSIF, ...
242 dec_indent(env(I,Stream,K,Opts),env(I1,Stream,K,Opts)) :-
243 (I>0 -> get_indent_spaces(Opts,Nr),
244 (member(half_indent_elsif,Opts) -> I1 is I-(Nr//2) % ELSIF is slightly indented
245 ; I1 is I-Nr)
246 ; I1=I).
247
248 update_indent(env(I,Stream,K,Opts),Delta,env(I1,Stream,K,Opts)) :-
249 get_indent_spaces(Opts,Nr), I1 is I+Nr*Delta.
250
251
252 is_ident_relevant_code(0'{,1).
253 is_ident_relevant_code(0'},-1).
254 is_ident_relevant_code(0'(,1).
255 is_ident_relevant_code(0'),-1).
256 is_ident_relevant_code(0'[,1).
257 is_ident_relevant_code(0'],-1).
258 is_ident_relevant_code(0'|,0).
259 % TODO: should we treat •, . in quantifiers also like this?
260 % TODO: also treat =>, &, or, ... in a similar fashion?
261
262 is_indent_relevant_keyword('ANY',1).
263 is_indent_relevant_keyword('ASSERT',1).
264 is_indent_relevant_keyword('BEGIN',1).
265 is_indent_relevant_keyword('CASE',1).
266 is_indent_relevant_keyword('CHOICE',1).
267 is_indent_relevant_keyword('EITHER',1). % CASE E OF EITHER ... OR ... ELSE ... END END: needs two ENDs
268 is_indent_relevant_keyword('IF',1).
269 is_indent_relevant_keyword('LET',1).
270 is_indent_relevant_keyword('PRE',1).
271 is_indent_relevant_keyword('SELECT',1).
272 is_indent_relevant_keyword('VAR',1).
273 is_indent_relevant_keyword('WHILE',1).
274 % SIGMA, PI : accompanied by parentheses which will force indent
275
276 % TODO: support rules_dsl
277 % is_indent_relevant_keyword('FOR',1).
278
279 is_indent_relevant_keyword('END',-1).
280
281
282 is_indent_relevant_keyword('BE',0).
283 is_indent_relevant_keyword('DO',0).
284 is_indent_relevant_keyword('ELSE',0).
285 is_indent_relevant_keyword('ELSIF',0).
286 is_indent_relevant_keyword('IN',0).
287 is_indent_relevant_keyword('OF',0).
288 is_indent_relevant_keyword('OR',0).
289 is_indent_relevant_keyword('THEN',0).
290 is_indent_relevant_keyword('WHEN',0).
291 is_indent_relevant_keyword('WHERE',0).
292 is_indent_relevant_keyword('WITH',0).
293 is_indent_relevant_keyword('WITNESS',0).
294
295
296