-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathligo2dox.php
executable file
·401 lines (363 loc) · 20 KB
/
ligo2dox.php
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
#!/usr/bin/php
<?php
///RU \file
///RU Преобразование кода LIGO для автодокументирования с помощью Doxygen
///RU Скрипт разработан для преобработки проекта на LIGO пофайлово в C++ подобный код, чтобы Doxygen успешно распознал в них функции, переменные, классы.
///RU Разрабатывался и тестировался в Debian 11 / PHP 7.4.
///RU \author Дмитрий Дмитриев
///RU \date 02.2022
///RU \copyright MIT
///EN \file
///EN Convert LIGO code for auto-documenting by Doxygen
///EN The script is designed for preprocessing LIGO code project to C++ like code, in order to Doxygen recognize in it variables, functions, classes.
///EN Developed and testing under Debian 11 / PHP 7.4.
///EN \author Dmitrii Dmitriev
///EN \date 02.2022
///EN \copyright MIT
class Ligo2Dox {
///RU Файл для обработки, '-' - stdin
///EN File for patch, '-' - stdin
protected static $filename = '';
protected static $saved = [];///RU Сохраненные директивы, комментарии
public static function run(array $argv):bool {
if (!static::parseArgs($argv)) return false;
return static::patch();
}
///RU Разбор аргументов командной строки
///EN Parse command line arguments
protected static function parseArgs(array $argv): bool {
$errors = [];
for ($i = 1; $i < count($argv); ++$i) {
$arg = $argv[$i];
if (!static::$filename) {
if ('-' !== $arg) {
if (!file_exists($arg)) $errors[] = "Not found file '$arg'";
}
static::$filename = $arg;
} else $errors[] = "Try use many files in '$arg'";
}
if (!static::$filename) $errors[] = "Filename is required";
if ($errors) {
static::stderr(implode("\n", $errors));
static::usage($argv, true);
return false;
}
return true;
}
///RU Вывод справки о параметрах
///EN Print usage of script
public static function usage($argv, bool $tostderr = false):void {
fwrite($tostderr ? STDERR : STDOUT, implode("\n", [
"Usage: ".basename($argv[0])." FILENAME|-, where",
"FILENAME - path to *.ligo file for patching, '-' - use stdin",
"Output always to stdout",
])."\n\n");
}
///EN Patch file/stdin content
protected static function patch():bool {
if ('-' === static::$filename) {
$content = '';
while (($buf = fread(STDIN, 128 * 1024 * 1024))) {
$content .= $buf;
usleep(50000);
}
} else $content = file_get_contents(static::$filename);
$content = preg_replace('/(\[@[^]]+]| +block +)/u', ' ', $content);///RU Зачищаем директивы компилятора и block
// //#define X -> #define X 0
if (preg_match_all('/(?<=\n)\/\/#[dD]efine +(?<define>[^ \n]+)/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$ligo = $dligo[0];
$content = static::replace($content, $ligo, $dligo[1] + $dofs, strlen($ligo), '#define '.$m['define'][$i][0].' false', $incofs);
if ($incofs) $dofs += $incofs;
}
}
$classofs = 0;//RU Куда вставлять class {
$endclassofs = -1;//RU Куда вставлять }
if (preg_match('/((?:^|\n)#[a-z]+[^\n]*)+/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$classofs = $m[0][1] + strlen($m[0][0]) + 1;
}
if (preg_match_all('/(?:^|\n)#include\s+[^\n]+/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$lastinclude = $m[0][count($m[0]) - 1];
$classofs = $lastinclude[1] + strlen($lastinclude[0]) + 1;
}
if (preg_match('/^#if/u', $content)) {
if (preg_match('/\n#endif\s*(\/\/[^\n]*)?\s*$/', $content, $m, PREG_OFFSET_CAPTURE)) {
$endclassofs = $m[0][1];
}
}
$content = static::saveDecorations($content);
$relexem = '[_a-zA-Z][_a-zA-Z0-9]*';
// module -> class
if (preg_match_all('/(?<=\n) *module +(?<module>'.$relexem.') +is +{/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$ligo = $dligo[0]; $len = strlen($ligo); $ofs = $dligo[1] + $dofs;
$content = static::replace($content, $ligo, $ofs, $len, 'class '.$m['module'][$i][0].' { public:', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
}
} else {
$class = '';
// function main -> class
if ((preg_match('/function\s+main\s*\(/u', $content))) {
$class = '-' === static::$filename ? 'Contract' : preg_replace('/\.[^.]+$/', '', basename(static::$filename));
}
if ('-' !== static::$filename) {
$dir = dirname(static::$filename);
$dirname = basename($dir);
if (file_exists(dirname($dir).DIRECTORY_SEPARATOR.$dirname.'.ligo')) $class = $dirname;
}
// class { public: CONTENT }
if ($class) {
$class = "class $class { public: ";
$content = substr($content, 0, $classofs).$class.substr($content, $classofs);
static::incSavedOfs($classofs, strlen($class));
if ($endclassofs < 0) $content .= "\n}\n";
else {
$endclassofs += strlen($class);
$endclass = "\n}";
$content = substr($content, 0, $endclassofs).$endclass.substr($content, $endclassofs);
static::incSavedOfs($endclassofs, strlen($endclass));
}
}
}
// type is record -> typedef struct
$refield = ' *(?<name>'.$relexem.') *: *(?<type>[^;]+ *;)';
if (preg_match_all('/(?<before>(?<=\n) *type +(?<type>'.$relexem.') +is +record *\[)(?<fields>[^]]*)(?<close>]\s*;?)/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$rfields = $fields = $m['fields'][$i][0];
preg_match_all('/'.$refield.'/u', $rfields, $mv, PREG_OFFSET_CAPTURE);
$djofs = 0;
foreach($mv[0] as $j => $fdata) {
$jofs = $fdata[1] + $djofs;
$rfields = static::replace($rfields, $fdata[0], $jofs, strlen($fdata[0]), static::patchType(rtrim($mv['type'][$j][0], ';')).' '.$mv['name'][$j][0].';', $incofs);
$djofs += $incofs;
}
$ofs = $m['before'][$i][1] + $dofs;
$content = static::replace($content, $m['before'][$i][0], $ofs, strlen($m['before'][$i][0]), 'typedef struct '.$m['type'][$i][0].' {', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
$ofs = $m['fields'][$i][1] + $dofs;
$content = static::replace($content, $fields, $ofs, strlen($fields), $rfields, $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
$ofs = $m['close'][$i][1] + $dofs;
$content = static::replace($content, $m['close'][$i][0], $ofs, strlen($m['close'][$i][0]), '};', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
}
}
// type is
if (preg_match_all('/(?<before>(?<=\n) *type +(?<name>'.$relexem.') +is)(?<type>[^\n|;]+;?)/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$ofs = $dligo[1] + $dofs;
$content = static::replace($content, $dligo[0], $ofs, strlen($dligo[0]), 'typedef '.static::patchType(rtrim($m['type'][$i][0], ';')).' '.$m['name'][$i][0].';', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
}
}
// type is | -> enum
$recase = '(?<precase>(\n\s*)*\|?\s*)(?<case>[A-Z][_a-zA-Z0-9]*)(?<aftcase>\s*[^\n|;]*)';
if (preg_match_all('/(?<before>(?<=\n) *type +(?<name>'.$relexem.') +is)(?<cases>\s*('.$recase.')+)/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$rcases = $m['cases'][$i][0];
preg_match_all('/'.$recase.'/u', $rcases, $mv, PREG_OFFSET_CAPTURE);
$djofs = 0; $c = count($mv[0]);
foreach($mv[0] as $j => $fdata) {
$jofs = $fdata[1] + $djofs;
$precase = static::spaces($mv['precase'][$j][0]);
$aftcase = static::spaces($mv['aftcase'][$j][0]);
if (' ' === substr($precase, -1)) $precase = substr($precase, 0, -1);
else if (' ' === substr($aftcase, 0, 1)) $aftcase = substr($aftcase, 1);
$rcases = static::replace($rcases, $fdata[0], $jofs, strlen($fdata[0]), $precase.$mv['case'][$j][0].($j == ($c - 1) ? '}' : ',').$aftcase, $incofs);
$djofs += $incofs;
}
$ofs = $m['before'][$i][1] + $dofs;
$content = static::replace($content, $m['before'][$i][0], $ofs, strlen($m['before'][$i][0]), 'enum '.$m['name'][$i][0].' {', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
$ofs = $m['cases'][$i][1] + $dofs;
$content = static::replace($content, $m['cases'][$i][0], $ofs, strlen($m['cases'][$i][0]), $rcases, $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
}
}
// const
if (preg_match_all('/(?:(?<=\n)| )const +(?<name>'.$relexem.') *(?:: *(?<type>[^=;:]+) *)?=/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$ofs = $dligo[1] + $dofs;
$content = static::replace($content, $dligo[0], $ofs, strlen($dligo[0]), 'const '.static::patchType($m['type'][$i][0] ?? '').' '.$m['name'][$i][0].' =', $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
}
}
// function
$revar = '\s*(?<const>const|var) +(?<name>'.$relexem.')\s*:\s*(?<type>[^;]+);?';
if (preg_match_all('/(?<=\n) *function +(?<func>'.$relexem.')\s*\((?<vars>(?:'.$revar.')+)\)\s*:(?<return>.*?)is'.
'(?<open>\s*{'.// is block {
'|\s*case\s+.+\sof[^[]+(?<qb>\[(?>[^[\]]|(?&qb))*+])'.// case ... []
'|\s*[^\s(]+(?<rb>\((?>[^()]|(?&rb))*+\))'.// ...()
'|\s*[^;]+;'.// ...;
')/u', $content, $m, PREG_OFFSET_CAPTURE)) {
$dofs = 0;
foreach ($m[0] as $i => $dligo) {
$ligo = $dligo[0]; $len = strlen($dligo[0]); $ofs = $dligo[1] + $dofs;
preg_match_all('/'.$revar.'/u', $m['vars'][$i][0], $mv);
$in = [];
foreach($mv['name'] as $j => $name) {
$in[] = ('const' === ($mv['const'][$j] ?? '') ? 'const ' : '').static::patchType($mv['type'][$j]).' '.$name;
}
$open = $m['open'][$i][0]; $openlen = strlen($open);
$isBlockOpen = preg_match('/{$/u', $open);
if (!$isBlockOpen) {
$content = substr($content, 0, $ofs + $len - $openlen).'{'.substr($content, $ofs + $len - $openlen);
static::incSavedOfs($ofs + $len - $openlen, 1);
$content = substr($content, 0, $ofs + $len + 1).'}'.substr($content, $ofs + $len + 1);
static::incSavedOfs($ofs + $len + 1, 1);
}
$func = static::patchType($m['return'][$i][0]).' '.$m['func'][$i][0].'('.implode(',', $in).') ';
$content = static::replace($content, substr($ligo, 0, $len - $openlen), $ofs, $len - $openlen, $func, $incofs);
if ($incofs) {
static::incSavedOfs($ofs, $incofs);
$dofs += $incofs;
}
if (!$isBlockOpen) $dofs += 2;
}
}
// with ... ->
if (preg_match_all('/(?<=[ }])with +([_a-zA-Z][_a-zA-Z0-9]*|\((?>[^()]|(?1))*+\))/u', $content, $m, PREG_OFFSET_CAPTURE)) {
foreach ($m[0] as $i => $dligo) {
$ligo = $dligo[0];
$content = static::replace($content, $ligo, $dligo[1], strlen($ligo), static::spaces($ligo), $incofs);
}
}
// := -> =
$content = str_replace(':=', ' =', $content);
$content = static::restoreDecorations($content);
echo $content;
return true;
}
protected static function replace(string $content, string $ligo, int $ofs, int $len, string $replace, &$incofs = null):string {
$llines = count(explode("\n", $ligo)); $rlines = count(explode("\n", $replace));
if ($rlines < $llines) $replace = str_repeat("\n", $llines - $rlines).$replace;///RU Сохраняем кол-во строк
$newlen = strlen($replace);
if ($newlen > $len) {
$incofs = $newlen - $len;
} else {
$replace = str_repeat(' ', $len - $newlen).$replace;
$incofs = 0;
}
$sligo = substr($content, $ofs, $len);
if ($ligo !== $sligo) static::stderr("Replace error: '$ligo' != '$sligo'");
//DEBUG static::stderr("$incofs\n'$ligo'\n ---> \n'$replace'\n");
$content = substr($content, 0, $ofs).$replace.substr($content, $ofs + $len);
return $content;
}
protected static function patchType(string $type):string {
$type = trim($type);
if (!$type) return 'auto';
if (preg_match('/^option\((.*)\)$/u', $type, $mt)) {
return 'option<'.static::patchType($mt[1]).'>';
}
$types = explode('*', $type);
if (count($types) > 1) {
$subtypes = [];
foreach ($types as $subtype) {
$subtype =rtrim($subtype, '*');
$subtypes[] = static::patchType($subtype);
}
return (2 == count($subtypes) ? 'pair' : 'tuple').'<'.implode(',', $subtypes).'>';
} else {
if (preg_match('/^map\((.*)\)$/ui', $type, $mm)) {
$types = explode(',', $mm[1]);
return 'map<'.static::patchType(trim($types[0], '()')).','.static::patchType(trim($types[1], '()')).'>';
}
if (preg_match('/^big_map\((.*)\)$/ui', $type, $mm)) {
$types = explode(',', $mm[1]);
return 'big_map<'.static::patchType(trim($types[0], '()')).','.static::patchType(trim($types[1], '()')).'>';
}
if (preg_match('/^(list|set|contract)\((.*)\)$/ui', $type, $ml)) {
if ('list' === strtolower($ml[1])) return 'list<'.static::patchType($ml[2]).'>';
else if ('set' === strtolower($ml[1])) return 'set<'.static::patchType($ml[2]).'>';
else return 'contract<'.static::patchType($ml[2]).'>';
}
if (preg_match('/(?<module>[_a-zA-Z0-9]+)\.(?<type>[_a-zA-Z0-9]+)/u', $type, $mm)) {
return $mm['module'].'::'.$mm['type'];
}
return $type;
}
}
protected static function incSavedOfs(int $from, int $inc):void {
foreach (static::$saved as &$save) {
if ($save['ofs'] >= $from) $save['ofs'] += $inc;
}
unset($save);
}
///RU Извлечение, сохранение в переменную и замена пробелами такой же длины В БАЙТАХ директив, комментариев
protected static function saveDecorations(string $content):string {
//RU Извлекаем и заменяем пробелами такой же длины В БАЙТАХ директивы, комментарии
$redecor[] = '(?:^|\n)#(define|if|else|endif|include)[^\n]*';//RU Директивы препроцессора (строка целиком)
$redecor[] = preg_quote('//', '/').'[^\n]*(\n *'.preg_quote('//', '/').'[^\n]*)*';//RU Однострочные комментарии
$redecor[] = preg_quote('(*', '/').'[\\S\\s]*?'.preg_quote('*)', '/');//RU Многострочные комментарии
$redecor = '(?:'.implode('|', $redecor).')';
static::$saved = [];
if (preg_match_all('/'.$redecor.'/u', $content, $mc, PREG_OFFSET_CAPTURE)) {
foreach($mc[0] as $data) {
$s = $data[0]; $len = strlen($s);
///RU Заменяем С++ многострочными комментариями
if (('(*' === substr($s, 0, 2)) && ('*)' === substr($s, -2))) $s = '/*'.substr($s, 2, $len - 4).'*/';
$ofs = $data[1];
static::$saved[] = [
's' => $s,
'ofs' => $ofs,
'len' => $len
];
$s = static::spaces($s);
$content = substr($content, 0, $ofs).$s.substr($content, $ofs + $len);
}
}
return $content;
}
///RU Все, кроме переводов строки, заменяем пробелами по кол-ву байтов
protected static function spaces(string $s):string {
if ('' === $s) return $s;
$lines = explode("\n", $s);
foreach ($lines as &$line) $line = str_repeat(' ', strlen($line));
unset($line);
$s = implode("\n", $lines);
return $s;
}
protected static function restoreDecorations(string $content):string {
foreach (static::$saved as $data) {
['s' => $s, 'ofs' => $ofs, 'len' => $len] = $data;
$content = substr($content, 0, $ofs).$s.substr($content, $ofs + $len);
}
static::$saved = [];
return $content;
}
protected static function stderr(string $error):void {
fwrite(STDERR, $error."\n\n");
}
};
Ligo2Dox::run($argv);