Debian Codegraph @

mesonbuild/mformat.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2024 The Meson development team
3
4 from __future__ import annotations
5
6 import difflib
7 import re
8 import typing as T
9 from configparser import ConfigParser, MissingSectionHeaderError, ParsingError
10 from copy import deepcopy
11 from dataclasses import dataclass, field, fields, asdict
12 from pathlib import Path
13 import sys
14
15 from . import mparser
16 from .mesonlib import MesonException, pathname_sort_key
17 from .ast.postprocess import AstConditionLevel
18 from .ast.printer import RawPrinter
19 from .ast.visitor import FullAstVisitor
20 from .environment import build_filename
21
22 if T.TYPE_CHECKING:
23 import argparse
24 from typing_extensions import Literal
25
26
27 class DefaultConfigParser(ConfigParser):
28
29 def __init__(self, delimiters: T.Tuple[str, ...] = ('=', ':')):
30 super().__init__(delimiters=delimiters, interpolation=None)
31
32 def read_default(self, filename: Path) -> None:
33 if not filename.exists():
34 raise MesonException(f'Configuration file {filename} not found')
35 try:
36 super().read(filename, encoding='utf-8')
37 except MissingSectionHeaderError:
38 self.read_string(f'[{self.default_section}]\n' + filename.read_text(encoding='utf-8'))
39
40 def getstr(self, section: str, key: str, fallback: T.Optional[str] = None) -> T.Optional[str]:
41 value: T.Optional[str] = self.get(section, key, fallback=fallback)
42 if value:
43 value = value.strip('"').strip("'")
44 return value
45
46
47 def match_path(filename: str, pattern: str) -> bool:
48 '''recursive glob match for editorconfig sections'''
49 index = 0
50 num_ranges: T.List[T.Tuple[int, int]] = []
51
52 def curl_replace(m: re.Match) -> str:
53 nonlocal index
54
55 if '\\.\\.' in m[1]:
56 index += 1
57 low, high = m[1].split('\\.\\.')
58 num_ranges.append((int(low), int(high)))
59 return f'(?P<num{index}>-?[0-9]+)'
60 else:
61 return T.cast(str, m[1].replace(',', '|'))
62
63 pattern_re = pattern.replace('.', '\\.')
64 pattern_re = re.sub(r'(?<!\\)\?', '.', pattern_re) # ? -> .
65 pattern_re = re.sub(r'(?<![\\\*])\*(?!\*)', '([^/]*)', pattern_re) # * -> ([^/]*)
66 pattern_re = re.sub(r'(?<!\\)\*\*', '(.*)', pattern_re) # ** -> (.*)
67 pattern_re = re.sub(r'(?<!\\)\[!(.*?[^\\])\]', r'([^\1])', pattern_re) # [!name] -> [^name]
68 pattern_re = re.sub(r'(?<!\\)\{(.*?[^\\])}', curl_replace, pattern_re) # {}
69 if pattern.startswith('/'):
70 pattern_re = '^' + pattern_re
71 pattern_re += '$'
72
73 m = re.search(pattern_re, filename)
74 if m is None:
75 return False
76
77 for i in range(index):
78 try:
79 val = int(m[f'num{i+1}'])
80 if not num_ranges[i][0] <= val <= num_ranges[i][1]:
81 return False
82 except ValueError:
83 return False
84
85 return True
86
87
88 @dataclass
89 class EditorConfig:
90
91 indent_style: T.Optional[Literal['space', 'tab']] = field(default=None, metadata={'getter': DefaultConfigParser.get})
92 indent_size: T.Optional[int] = field(default=None, metadata={'getter': DefaultConfigParser.getint})
93 tab_width: T.Optional[int] = field(default=None, metadata={'getter': DefaultConfigParser.getint})
94 end_of_line: T.Optional[Literal['lf', 'cr', 'crlf']] = field(default=None, metadata={'getter': DefaultConfigParser.get})
95 charset: T.Optional[Literal['latin1', 'utf-8', 'utf-8-bom', 'utf-16be', 'utf-16le']] = field(default=None, metadata={'getter': DefaultConfigParser.get})
96 trim_trailing_whitespace: T.Optional[bool] = field(default=None, metadata={'getter': DefaultConfigParser.getboolean})
97 insert_final_newline: T.Optional[bool] = field(default=None, metadata={'getter': DefaultConfigParser.getboolean})
98 max_line_length: T.Optional[T.Union[Literal['off'], int]] = field(default=None, metadata={'getter': DefaultConfigParser.get})
99
100
101 @dataclass
102 class FormatterConfig:
103
104 # Config keys compatible with muon
105 max_line_length: T.Optional[int] = field(
106 default=None,
107 metadata={'getter': DefaultConfigParser.getint,
108 'default': 80,
109 })
110 indent_by: T.Optional[str] = field(
111 default=None,
112 metadata={'getter': DefaultConfigParser.getstr,
113 'default': ' ',
114 })
115 space_array: T.Optional[bool] = field(
116 default=None,
117 metadata={'getter': DefaultConfigParser.getboolean,
118 'default': False,
119 })
120 kwargs_force_multiline: T.Optional[bool] = field(
121 default=None, # kwa_ml
122 metadata={'getter': DefaultConfigParser.getboolean,
123 'default': False,
124 })
125 wide_colon: T.Optional[bool] = field(
126 default=None,
127 metadata={'getter': DefaultConfigParser.getboolean,
128 'default': False,
129 })
130 no_single_comma_function: T.Optional[bool] = field(
131 default=None,
132 metadata={'getter': DefaultConfigParser.getboolean,
133 'default': False,
134 })
135
136 # Additional config keys
137 end_of_line: T.Optional[Literal['cr', 'lf', 'crlf', 'native']] = field(
138 default=None,
139 metadata={'getter': DefaultConfigParser.getstr,
140 'default': 'native',
141 })
142 indent_before_comments: T.Optional[str] = field(
143 default=None,
144 metadata={'getter': DefaultConfigParser.getstr,
145 'default': ' ',
146 })
147 simplify_string_literals: T.Optional[bool] = field(
148 default=None,
149 metadata={'getter': DefaultConfigParser.getboolean,
150 'default': True,
151 })
152 insert_final_newline: T.Optional[bool] = field(
153 default=None,
154 metadata={'getter': DefaultConfigParser.getboolean,
155 'default': True,
156 })
157 tab_width: T.Optional[int] = field(
158 default=None,
159 metadata={'getter': DefaultConfigParser.getint,
160 'default': 4,
161 }
162 )
163 sort_files: T.Optional[bool] = field(
164 default=None,
165 metadata={'getter': DefaultConfigParser.getboolean,
166 'default': False,
167 })
168 group_arg_value: T.Optional[bool] = field(
169 default=None,
170 metadata={'getter': DefaultConfigParser.getboolean,
171 'default': False,
172 })
173 use_editor_config: T.Optional[bool] = field(
174 default=None,
175 metadata={'getter': DefaultConfigParser.getboolean,
176 'default': False,
177 })
178
179 @classmethod
180 def default(cls) -> FormatterConfig:
181 defaults = {f.name: f.metadata['default'] for f in fields(cls)}
182 return cls(**defaults)
183
184 def update(self, config: FormatterConfig) -> FormatterConfig:
185 """Returns copy of self updated with other config"""
186 new_config = deepcopy(self)
187 for key, value in asdict(config).items():
188 if value is not None:
189 setattr(new_config, key, value)
190 return new_config
191
192 def with_editorconfig(self, editorconfig: EditorConfig) -> FormatterConfig:
193 """Returns copy of self updated with editorconfig"""
194 config = deepcopy(self)
195
196 if editorconfig.indent_style == 'space':
197 indent_size = editorconfig.indent_size or 4
198 config.indent_by = indent_size * ' '
199 elif editorconfig.indent_style == 'tab':
200 config.indent_by = '\t'
201 elif editorconfig.indent_size:
202 config.indent_by = editorconfig.indent_size * ' '
203
204 if editorconfig.max_line_length == 'off':
205 config.max_line_length = 0
206 elif editorconfig.max_line_length:
207 config.max_line_length = int(editorconfig.max_line_length)
208
209 if editorconfig.end_of_line:
210 config.end_of_line = editorconfig.end_of_line
211 if editorconfig.insert_final_newline:
212 config.insert_final_newline = editorconfig.insert_final_newline
213 if editorconfig.tab_width:
214 config.tab_width = editorconfig.tab_width
215
216 return config
217
218 @property
219 def newline(self) -> T.Optional[str]:
220 if self.end_of_line == 'crlf':
221 return '\r\n'
222 if self.end_of_line == 'lf':
223 return '\n'
224 if self.end_of_line == 'cr':
225 return '\r'
226 return None
227
228
229 class MultilineArgumentDetector(FullAstVisitor):
230
231 def __init__(self, config: FormatterConfig):
232 self.config = config
233 self.is_multiline = False
234
235 def enter_node(self, node: mparser.BaseNode) -> None:
236 if node.whitespaces and '#' in node.whitespaces.value:
237 self.is_multiline = True
238
239 elif isinstance(node, mparser.StringNode) and node.is_multiline:
240 self.is_multiline = True
241
242 def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
243 if node.is_multiline:
244 self.is_multiline = True
245
246 nargs = len(node)
247 if nargs and nargs == len(node.commas):
248 self.is_multiline = True
249
250 if self.is_multiline:
251 return
252
253 if self.config.kwargs_force_multiline and node.kwargs:
254 self.is_multiline = True
255
256 super().visit_ArgumentNode(node)
257
258
259 class MultilineParenthesesDetector(FullAstVisitor):
260
261 def __init__(self) -> None:
262 self.last_whitespaces: T.Optional[mparser.WhitespaceNode] = None
263
264 def enter_node(self, node: mparser.BaseNode) -> None:
265 self.last_whitespaces = None
266
267 def exit_node(self, node: mparser.BaseNode) -> None:
268 if node.whitespaces and node.whitespaces.value:
269 self.last_whitespaces = node.whitespaces
270
271
272 class TrimWhitespaces(FullAstVisitor):
273
274 def __init__(self, config: FormatterConfig):
275 self.config = config
276
277 self.in_block_comments = False
278 self.in_arguments = 0
279 self.indent_comments = ''
280
281 def visit_default_func(self, node: mparser.BaseNode) -> None:
282 self.enter_node(node)
283 node.whitespaces.accept(self)
284
285 def enter_node(self, node: mparser.BaseNode) -> None:
286 if isinstance(node, mparser.WhitespaceNode):
287 return
288 if not node.whitespaces:
289 # Ensure every node has a whitespace node
290 node.whitespaces = mparser.WhitespaceNode(mparser.Token('whitespace', node.filename, 0, 0, 0, (0, 0), ''))
291 node.whitespaces.condition_level = node.condition_level
292
293 def exit_node(self, node: mparser.BaseNode) -> None:
294 pass
295
296 def move_whitespaces(self, from_node: mparser.BaseNode, to_node: mparser.BaseNode) -> None:
297 to_node.whitespaces.value = from_node.whitespaces.value + to_node.whitespaces.value
298 to_node.whitespaces.is_continuation = from_node.whitespaces.is_continuation
299 from_node.whitespaces = None
300 to_node.whitespaces.accept(self)
301
302 def add_space_after(self, node: mparser.BaseNode) -> None:
303 if not node.whitespaces.value:
304 node.whitespaces.value = ' '
305 elif '#' not in node.whitespaces.value:
306 node.whitespaces.value = ' '
307
308 def add_nl_after(self, node: mparser.BaseNode, force: bool = False) -> None:
309 if not node.whitespaces.value:
310 node.whitespaces.value = '\n'
311 elif force and not node.whitespaces.value.endswith('\n'):
312 node.whitespaces.value += '\n'
313
314 def dedent(self, value: str) -> str:
315 if value.endswith(self.config.indent_by):
316 value = value[:-len(self.config.indent_by)]
317 return value
318
319 def sort_arguments(self, node: mparser.ArgumentNode) -> None:
320 def sort_key(arg: mparser.BaseNode) -> tuple[tuple[bool, tuple[int | str, ...]], ...]:
321 if isinstance(arg, mparser.StringNode):
322 val = arg.raw_value
323 else:
324 val = getattr(node, 'value', '')
325 return pathname_sort_key(val)
326
327 node.arguments.sort(key=sort_key)
328
329 def visit_EmptyNode(self, node: mparser.EmptyNode) -> None:
330 self.enter_node(node)
331 self.in_block_comments = True
332 node.whitespaces.accept(self)
333 self.in_block_comments = False
334
335 def visit_WhitespaceNode(self, node: mparser.WhitespaceNode) -> None:
336 lines = node.value.splitlines(keepends=True)
337 node.value = ''
338 in_block_comments = self.in_block_comments
339 with_comments = ['#' in line for line in lines] + [False]
340 for i, line in enumerate(lines):
341 has_nl = line.endswith('\n')
342 line = line.strip()
343 if line.startswith('\\'):
344 node.value += ' ' # add space before \
345 node.is_continuation = True
346 elif line.startswith('#'):
347 if not in_block_comments:
348 node.value += self.config.indent_before_comments
349 else:
350 node.value += self.indent_comments
351 node.value += line
352 if has_nl and (line or with_comments[i+1] or not self.in_arguments):
353 node.value += '\n'
354 in_block_comments = True
355 if node.value.endswith('\n'):
356 node.value += self.indent_comments
357 if node.is_continuation:
358 node.value += self.config.indent_by
359
360 def visit_SymbolNode(self, node: mparser.SymbolNode) -> None:
361 super().visit_SymbolNode(node)
362 if node.value in "([{" and node.whitespaces.value == '\n':
363 node.whitespaces.value = ''
364 node.whitespaces.accept(self)
365
366 def visit_StringNode(self, node: mparser.StringNode) -> None:
367 self.enter_node(node)
368
369 if self.config.simplify_string_literals:
370 if node.is_multiline and not any(x in node.value for x in ['\n', "'"]):
371 node.is_multiline = False
372 node.value = node.escape()
373
374 if node.is_fstring and '@' not in node.value:
375 node.is_fstring = False
376
377 node.whitespaces.accept(self)
378
379 def visit_UnaryOperatorNode(self, node: mparser.UnaryOperatorNode) -> None:
380 super().visit_UnaryOperatorNode(node)
381 self.move_whitespaces(node.value, node)
382
383 def visit_NotNode(self, node: mparser.NotNode) -> None:
384 super().visit_UnaryOperatorNode(node)
385 if not node.operator.whitespaces.value:
386 node.operator.whitespaces.value = ' '
387 self.move_whitespaces(node.value, node)
388
389 def visit_BinaryOperatorNode(self, node: mparser.BinaryOperatorNode) -> None:
390 super().visit_BinaryOperatorNode(node)
391 self.add_space_after(node.left)
392 self.add_space_after(node.operator)
393 self.move_whitespaces(node.right, node)
394
395 def visit_ArrayNode(self, node: mparser.ArrayNode) -> None:
396 super().visit_ArrayNode(node)
397 self.move_whitespaces(node.rbracket, node)
398
399 if node.lbracket.whitespaces.value:
400 node.args.is_multiline = True
401 if node.args.arguments and not node.args.is_multiline and self.config.space_array:
402 self.add_space_after(node.lbracket)
403 self.add_space_after(node.args)
404 if not node.args.arguments:
405 self.move_whitespaces(node.lbracket, node.args)
406
407 def visit_DictNode(self, node: mparser.DictNode) -> None:
408 super().visit_DictNode(node)
409 self.move_whitespaces(node.rcurl, node)
410
411 if node.lcurl.whitespaces.value:
412 node.args.is_multiline = True
413
414 def visit_CodeBlockNode(self, node: mparser.CodeBlockNode) -> None:
415 self.enter_node(node)
416 if node.pre_whitespaces:
417 self.in_block_comments = True
418 node.pre_whitespaces.accept(self)
419 self.in_block_comments = False
420 else:
421 node.pre_whitespaces = mparser.WhitespaceNode(mparser.Token('whitespace', node.filename, 0, 0, 0, (0, 0), ''))
422 node.pre_whitespaces.block_indent = True
423
424 for i in node.lines:
425 i.accept(self)
426 self.exit_node(node)
427
428 if node.lines:
429 self.move_whitespaces(node.lines[-1], node)
430 else:
431 node.whitespaces.value = node.pre_whitespaces.value + node.whitespaces.value
432 node.pre_whitespaces.value = ''
433 self.in_block_comments = True
434 node.whitespaces.accept(self)
435 self.in_block_comments = False
436
437 if node.condition_level == 0 and self.config.insert_final_newline:
438 self.add_nl_after(node, force=True)
439
440 indent = node.condition_level * self.config.indent_by
441 if indent and node.lines:
442 node.pre_whitespaces.value += indent
443 for line in node.lines[:-1]:
444 line.whitespaces.value += indent
445
446 def visit_IndexNode(self, node: mparser.IndexNode) -> None:
447 super().visit_IndexNode(node)
448 self.move_whitespaces(node.rbracket, node)
449
450 def visit_MethodNode(self, node: mparser.MethodNode) -> None:
451 super().visit_MethodNode(node)
452 self.move_whitespaces(node.rpar, node)
453
454 if node.lpar.whitespaces.value:
455 node.args.is_multiline = True
456
457 def visit_FunctionNode(self, node: mparser.FunctionNode) -> None:
458 if node.func_name.value == 'files':
459 if self.config.sort_files:
460 self.sort_arguments(node.args)
461
462 if len(node.args.arguments) == 1 and not node.args.kwargs:
463 arg = node.args.arguments[0]
464 if isinstance(arg, mparser.ArrayNode):
465 if not arg.lbracket.whitespaces or not arg.lbracket.whitespaces.value.strip():
466 # files([...]) -> files(...)
467 node.args = arg.args
468
469 super().visit_FunctionNode(node)
470 self.move_whitespaces(node.rpar, node)
471
472 if node.lpar.whitespaces.value:
473 node.args.is_multiline = True
474
475 def visit_AssignmentNode(self, node: mparser.AssignmentNode) -> None:
476 super().visit_AssignmentNode(node)
477 self.add_space_after(node.var_name)
478 self.add_space_after(node.operator)
479 self.move_whitespaces(node.value, node)
480
481 def visit_ForeachClauseNode(self, node: mparser.ForeachClauseNode) -> None:
482 super().visit_ForeachClauseNode(node)
483 self.add_space_after(node.foreach_)
484 self.add_space_after(node.varnames[-1])
485 for comma in node.commas:
486 self.add_space_after(comma)
487 self.add_space_after(node.colon)
488
489 node.block.whitespaces.value += node.condition_level * self.config.indent_by
490 node.block.whitespaces.block_indent = True
491
492 self.move_whitespaces(node.endforeach, node)
493
494 def visit_IfClauseNode(self, node: mparser.IfClauseNode) -> None:
495 super().visit_IfClauseNode(node)
496 self.move_whitespaces(node.endif, node)
497
498 for if_node in node.ifs:
499 if_node.whitespaces.value += node.condition_level * self.config.indent_by
500 if isinstance(node.elseblock, mparser.ElseNode):
501 node.elseblock.whitespaces.value += node.condition_level * self.config.indent_by
502
503 def visit_IfNode(self, node: mparser.IfNode) -> None:
504 super().visit_IfNode(node)
505 self.add_space_after(node.if_)
506 self.in_block_comments = True
507 self.move_whitespaces(node.block, node)
508 self.in_block_comments = False
509 node.whitespaces.condition_level = node.condition_level + 1
510 node.whitespaces.block_indent = True
511
512 def visit_ElseNode(self, node: mparser.ElseNode) -> None:
513 super().visit_ElseNode(node)
514 self.in_block_comments = True
515 self.move_whitespaces(node.block, node)
516 self.in_block_comments = False
517 node.whitespaces.condition_level = node.condition_level + 1
518 node.whitespaces.block_indent = True
519
520 def visit_TernaryNode(self, node: mparser.TernaryNode) -> None:
521 super().visit_TernaryNode(node)
522 self.add_space_after(node.condition)
523 self.add_space_after(node.questionmark)
524 self.add_space_after(node.trueblock)
525 self.add_space_after(node.colon)
526 self.move_whitespaces(node.falseblock, node)
527
528 def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
529 if not node.is_multiline:
530 ml_detector = MultilineArgumentDetector(self.config)
531 node.accept(ml_detector)
532 if ml_detector.is_multiline:
533 node.is_multiline = True
534
535 self.in_arguments += 1
536 super().visit_ArgumentNode(node)
537 self.in_arguments -= 1
538
539 if not node.arguments and not node.kwargs:
540 node.whitespaces.accept(self)
541 return
542
543 last_node: mparser.BaseNode
544 has_trailing_comma = len(node.commas) == len(node.arguments) + len(node.kwargs)
545 if has_trailing_comma:
546 last_node = node.commas[-1]
547 elif node.kwargs:
548 for last_node in node.kwargs.values():
549 pass
550 else:
551 last_node = node.arguments[-1]
552
553 self.move_whitespaces(last_node, node)
554
555 if not node.is_multiline and '#' not in node.whitespaces.value:
556 node.whitespaces.value = ''
557
558 def visit_ParenthesizedNode(self, node: mparser.ParenthesizedNode) -> None:
559 self.enter_node(node)
560
561 if node.lpar.whitespaces and '#' in node.lpar.whitespaces.value:
562 node.is_multiline = True
563
564 elif not node.is_multiline:
565 ml_detector = MultilineParenthesesDetector()
566 node.inner.accept(ml_detector)
567 if ml_detector.last_whitespaces and '\n' in ml_detector.last_whitespaces.value:
568 # We keep it multiline if last parenthesis is on a separate line
569 node.is_multiline = True
570
571 if node.is_multiline:
572 self.indent_comments += self.config.indent_by
573
574 node.lpar.accept(self)
575 node.inner.accept(self)
576
577 if node.is_multiline:
578 node.inner.whitespaces.value = self.dedent(node.inner.whitespaces.value)
579 self.indent_comments = self.dedent(self.indent_comments)
580 self.add_nl_after(node.inner)
581 else:
582 node.inner.whitespaces = None
583
584 node.rpar.accept(self)
585 self.move_whitespaces(node.rpar, node)
586
587
588 class ArgumentFormatter(FullAstVisitor):
589
590 def __init__(self, config: FormatterConfig):
591 self.config = config
592 self.level = 0
593 self.indent_after = False
594 self.is_function_arguments = False
595 self.par_level = 0
596
597 def add_space_after(self, node: mparser.BaseNode) -> None:
598 if not node.whitespaces.value:
599 node.whitespaces.value = ' '
600
601 def add_nl_after(self, node: mparser.BaseNode, indent: int) -> None:
602 if not node.whitespaces.value or node.whitespaces.value == ' ':
603 node.whitespaces.value = '\n'
604 indent_by = (node.condition_level + indent) * self.config.indent_by
605 if indent_by:
606 node.whitespaces.value = re.sub(rf'\n({self.config.indent_by})*', '\n' + indent_by, node.whitespaces.value)
607
608 def visit_ArrayNode(self, node: mparser.ArrayNode) -> None:
609 self.enter_node(node)
610 if node.args.is_multiline:
611 self.level += 1
612 if node.args.arguments:
613 self.add_nl_after(node.lbracket, indent=self.level)
614 node.lbracket.accept(self)
615 self.is_function_arguments = False
616 node.args.accept(self)
617 if node.args.is_multiline:
618 self.level -= 1
619 node.rbracket.accept(self)
620 self.exit_node(node)
621
622 def visit_DictNode(self, node: mparser.DictNode) -> None:
623 self.enter_node(node)
624 if node.args.is_multiline:
625 self.level += 1
626 if node.args.kwargs:
627 self.add_nl_after(node.lcurl, indent=self.level)
628 node.lcurl.accept(self)
629 self.is_function_arguments = False
630 node.args.accept(self)
631 if node.args.is_multiline:
632 self.level -= 1
633 node.rcurl.accept(self)
634 self.exit_node(node)
635
636 def visit_MethodNode(self, node: mparser.MethodNode) -> None:
637 self.enter_node(node)
638 node.source_object.accept(self)
639 is_cont = node.source_object.whitespaces and node.source_object.whitespaces.is_continuation
640 if is_cont:
641 self.level += 1
642 if node.args.is_multiline:
643 self.level += 1
644 self.add_nl_after(node.lpar, indent=self.level)
645 self.is_function_arguments = True
646 node.args.accept(self)
647 if node.args.is_multiline:
648 self.level -= 1
649 if is_cont:
650 self.level -= 1
651 self.exit_node(node)
652
653 def visit_FunctionNode(self, node: mparser.FunctionNode) -> None:
654 self.enter_node(node)
655 if node.args.is_multiline:
656 self.level += 1
657 self.add_nl_after(node.lpar, indent=self.level)
658 self.is_function_arguments = True
659 node.args.accept(self)
660 if node.args.is_multiline:
661 self.level -= 1
662 self.exit_node(node)
663
664 def visit_WhitespaceNode(self, node: mparser.WhitespaceNode) -> None:
665 lines = node.value.splitlines(keepends=True)
666 if lines:
667 indent = (node.condition_level + self.level) * self.config.indent_by
668 node.value = '' if node.block_indent else lines.pop(0)
669 for line in lines:
670 if '#' in line and not line.startswith(indent):
671 node.value += indent
672 node.value += line
673 if self.indent_after and node.value.endswith(('\n', self.config.indent_by)):
674 node.value += indent
675
676 def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
677 is_function_arguments = self.is_function_arguments # record it, because it may change when visiting children
678 super().visit_ArgumentNode(node)
679
680 for colon in node.colons:
681 self.add_space_after(colon)
682
683 if self.config.wide_colon:
684 for key in node.kwargs:
685 self.add_space_after(key)
686
687 arguments_count = len(node.arguments) + len(node.kwargs)
688 has_trailing_comma = node.commas and len(node.commas) == arguments_count
689 if node.is_multiline:
690 need_comma = True
691 if arguments_count == 1 and is_function_arguments:
692 need_comma = not self.config.no_single_comma_function
693
694 if need_comma and not has_trailing_comma:
695 comma = mparser.SymbolNode(mparser.Token('comma', node.filename, 0, 0, 0, (0, 0), ','))
696 comma.condition_level = node.condition_level
697 comma.whitespaces = mparser.WhitespaceNode(mparser.Token('whitespace', node.filename, 0, 0, 0, (0, 0), ''))
698 node.commas.append(comma)
699 elif has_trailing_comma and not need_comma:
700 node.commas.pop(-1)
701
702 arg_index = 0
703 if self.config.group_arg_value:
704 for arg in node.arguments[:-1]:
705 group_args = False
706 if isinstance(arg, mparser.StringNode) and arg.value.startswith('--') and arg.value != '--':
707 next_arg = node.arguments[arg_index + 1]
708 if isinstance(next_arg, mparser.StringNode) and not next_arg.value.startswith('--'):
709 group_args = True
710 if group_args:
711 # keep '--arg', 'value' on same line
712 self.add_space_after(node.commas[arg_index])
713 elif arg_index < len(node.commas):
714 self.add_nl_after(node.commas[arg_index], self.level + self.par_level)
715 arg_index += 1
716
717 for comma in node.commas[arg_index:-1]:
718 self.add_nl_after(comma, self.level + self.par_level)
719 if node.arguments or node.kwargs:
720 self.add_nl_after(node, self.level - 1)
721
722 else:
723 if has_trailing_comma and not (node.commas[-1].whitespaces and node.commas[-1].whitespaces.value):
724 node.commas.pop(-1)
725
726 for comma in node.commas:
727 self.add_space_after(comma)
728
729 self.exit_node(node)
730
731 def visit_ParenthesizedNode(self, node: mparser.ParenthesizedNode) -> None:
732 self.enter_node(node)
733 if node.is_multiline:
734 self.par_level += 1
735 current_indent_after = self.indent_after
736 self.indent_after = True
737 node.lpar.accept(self)
738 if node.is_multiline:
739 self.add_nl_after(node.lpar, indent=self.level + self.par_level)
740 node.inner.accept(self)
741 if node.is_multiline:
742 self.par_level -= 1
743 self.indent_after = current_indent_after
744 node.rpar.accept(self)
745 self.exit_node(node)
746
747 def visit_OrNode(self, node: mparser.OrNode) -> None:
748 self.enter_node(node)
749 node.left.accept(self)
750 if self.par_level:
751 self.add_nl_after(node.left, indent=self.level + self.par_level)
752 node.operator.accept(self)
753 node.right.accept(self)
754 self.exit_node(node)
755
756 def visit_AndNode(self, node: mparser.AndNode) -> None:
757 self.enter_node(node)
758 node.left.accept(self)
759 if self.par_level:
760 self.add_nl_after(node.left, indent=self.level + self.par_level)
761 node.operator.accept(self)
762 node.right.accept(self)
763 self.exit_node(node)
764
765
766 class ComputeLineLengths(FullAstVisitor):
767
768 def __init__(self, config: FormatterConfig, level: int):
769 self.config = config
770 self.lengths: T.List[int] = []
771 self.length = 0
772 self.argument_stack: T.List[mparser.ArgumentNode] = []
773 self.level = level
774 self.need_regenerate = False
775
776 def visit_default_func(self, node: mparser.BaseNode) -> None:
777 self.enter_node(node)
778 assert hasattr(node, 'value')
779 self.length += len(str(node.value))
780 self.exit_node(node)
781
782 def len(self, line: str) -> int:
783 '''Compute line length, including tab stops'''
784 parts = line.split('\t')
785 line_length = len(parts[0])
786 for p in parts[1:]:
787 tab_length = ((self.length + line_length) % self.config.tab_width) or self.config.tab_width
788 line_length += tab_length + len(p)
789 return line_length
790
791 def count_multiline(self, value: str) -> None:
792 lines = value.splitlines(keepends=True)
793 for line in lines:
794 if line.endswith('\n'):
795 self.lengths.append(self.length + self.len(line) - 1)
796 self.length = 0
797 else:
798 self.length += self.len(line)
799
800 def visit_WhitespaceNode(self, node: mparser.WhitespaceNode) -> None:
801 self.count_multiline(node.value)
802
803 def visit_EmptyNode(self, node: mparser.EmptyNode) -> None:
804 self.enter_node(node)
805 self.exit_node(node)
806
807 def visit_NumberNode(self, node: mparser.NumberNode) -> None:
808 self.enter_node(node)
809 self.length += len(node.raw_value)
810 self.exit_node(node)
811
812 def visit_StringNode(self, node: mparser.StringNode) -> None:
813 self.enter_node(node)
814 if node.is_fstring:
815 self.length += 1
816
817 if node.is_multiline:
818 self.length += 3
819 self.count_multiline(node.value)
820 self.length += 3
821 else:
822 self.length += self.len(node.raw_value) + 2
823
824 self.exit_node(node)
825
826 def visit_ContinueNode(self, node: mparser.ContinueNode) -> None:
827 self.enter_node(node)
828 self.length += len('continue')
829 self.exit_node(node)
830
831 def visit_BreakNode(self, node: mparser.BreakNode) -> None:
832 self.enter_node(node)
833 self.length += len('break')
834 self.exit_node(node)
835
836 def split_if_needed(self, node: mparser.ArgumentNode) -> None:
837 if len(node) and not node.is_multiline and self.length > self.config.max_line_length:
838 arg = self.argument_stack[self.level] if len(self.argument_stack) > self.level else node
839 arg.is_multiline = True
840 self.need_regenerate = True
841
842 def visit_ArgumentNode(self, node: mparser.ArgumentNode) -> None:
843 self.argument_stack.append(node)
844 super().visit_ArgumentNode(node)
845 self.split_if_needed(node)
846 self.argument_stack.pop(-1)
847
848 def visit_ArrayNode(self, node: mparser.ArrayNode) -> None:
849 self.enter_node(node)
850 node.lbracket.accept(self)
851 node.args.accept(self)
852 node.rbracket.accept(self)
853 self.split_if_needed(node.args) # split if closing bracket is too far
854 self.exit_node(node)
855
856 def visit_DictNode(self, node: mparser.DictNode) -> None:
857 self.enter_node(node)
858 node.lcurl.accept(self)
859 node.args.accept(self)
860 node.rcurl.accept(self)
861 self.split_if_needed(node.args) # split if closing bracket is too far
862 self.exit_node(node)
863
864 def visit_ParenthesizedNode(self, node: mparser.ParenthesizedNode) -> None:
865 self.enter_node(node)
866 node.lpar.accept(self)
867 node.inner.accept(self)
868 node.rpar.accept(self)
869 if not node.is_multiline and self.length > self.config.max_line_length:
870 node.is_multiline = True
871 self.need_regenerate = True
872 self.exit_node(node)
873
874
875 class SubdirFetcher(FullAstVisitor):
876
877 def __init__(self, current_dir: Path, fetch_subprojects: bool):
878 self.current_dir = current_dir
879 self.fetch_subprojects = fetch_subprojects
880 self.subdirs: T.List[Path] = []
881
882 def visit_FunctionNode(self, node: mparser.FunctionNode) -> None:
883 if self.fetch_subprojects and node.func_name.value == 'subproject':
884 if node.args.arguments and isinstance(node.args.arguments[0], mparser.StringNode):
885 subdir = node.args.arguments[0].value
886 self.subdirs.append(self.current_dir / 'subprojects' / subdir)
887 if node.func_name.value == 'subdir':
888 if node.args.arguments and isinstance(node.args.arguments[0], mparser.StringNode):
889 subdir = node.args.arguments[0].value
890 self.subdirs.append(self.current_dir / subdir)
891 super().visit_FunctionNode(node)
892
893
894 class Formatter:
895
896 def __init__(self, configuration_file: T.Optional[Path], use_editor_config: bool, fetch_subdirs: bool, fetch_subprojects: bool = False):
897 self.fetch_subdirs = fetch_subdirs
898 self.fetch_subprojects = fetch_subprojects
899 self.use_editor_config = use_editor_config
900 self.config = self.load_configuration(configuration_file)
901 self.current_config = self.config
902
903 self.current_dir = Path()
904 self.subdirs: T.List[Path] = []
905
906 def load_editor_config(self, source_file: Path) -> EditorConfig:
907 # See https://editorconfig.org/
908 config = EditorConfig()
909
910 if source_file == Path('STDIN'):
911 raise MesonException('Using editorconfig with stdin requires --source-file-path argument')
912
913 try:
914 source_file_path = source_file.resolve()
915 except FileNotFoundError:
916 raise MesonException(f'Unable to resolve path for "{source_file}"')
917
918 for p in source_file_path.parents:
919 editorconfig_file = p / '.editorconfig'
920 if not editorconfig_file.exists():
921 continue
922
923 cp = DefaultConfigParser(delimiters=('=',))
924 cp.read_default(editorconfig_file)
925
926 sections = [section for section in cp.sections() if match_path(source_file.as_posix(), section)]
927 for f in fields(config):
928 if getattr(cp, f.name, None) is not None:
929 continue # value already set from higher file
930
931 getter = f.metadata['getter']
932 for section in sections:
933 try:
934 value = getter(cp, section, f.name, fallback=None)
935 except ValueError as e:
936 raise MesonException(f'Invalid type for key "{f.name}" in "{editorconfig_file}" file:\n{e}') from e
937 if value is not None:
938 setattr(config, f.name, value)
939
940 # Root is not required except in the top level .editorconfig.
941 if cp.getboolean(cp.default_section, 'root', fallback=False):
942 break
943
944 return config
945
946 def load_configuration(self, configuration_file: T.Optional[Path]) -> FormatterConfig:
947 config = FormatterConfig()
948 if configuration_file:
949 cp = DefaultConfigParser()
950 try:
951 cp.read_default(configuration_file)
952 except ParsingError as e:
953 raise MesonException(f'Unable to parse configuration file "{configuration_file}":\n{e}') from e
954
955 extra_keys = sorted(set(cp.defaults()).difference(f.name for f in fields(config)))
956 if extra_keys:
957 raise MesonException(f'Unknown config keys: "{", ".join(extra_keys)}" in configuration file "{configuration_file}"')
958
959 for f in fields(config):
960 getter = f.metadata['getter']
961 try:
962 value = getter(cp, cp.default_section, f.name, fallback=None)
963 except ValueError as e:
964 raise MesonException(
965 f'Error parsing "{str(configuration_file)}", option "{f.name}", error: "{e!s}"')
966 if value is not None:
967 setattr(config, f.name, value)
968
969 if config.use_editor_config:
970 self.use_editor_config = True
971
972 return config
973
974 def format(self, code: str, source_file: Path) -> str:
975 self.current_dir = source_file.parent
976 self.current_config = FormatterConfig.default()
977 if self.use_editor_config:
978 self.current_config = self.current_config.with_editorconfig(self.load_editor_config(source_file))
979 self.current_config = self.current_config.update(self.config)
980
981 ast = mparser.Parser(code, source_file.as_posix()).parse()
982 if self.fetch_subdirs:
983 subdir_fetcher = SubdirFetcher(self.current_dir, self.fetch_subprojects)
984 ast.accept(subdir_fetcher)
985 self.subdirs = subdir_fetcher.subdirs
986
987 ast.accept(AstConditionLevel())
988 for level in range(5):
989 ast.accept(TrimWhitespaces(self.current_config))
990 ast.accept(ArgumentFormatter(self.current_config))
991
992 cll = ComputeLineLengths(self.current_config, level)
993 ast.accept(cll)
994 if not cll.need_regenerate:
995 break
996
997 printer = RawPrinter()
998 ast.accept(printer)
999 return printer.result
1000
1001
1002 def add_arguments(parser: argparse.ArgumentParser) -> None:
1003 inplace_group = parser.add_mutually_exclusive_group()
1004 inplace_group.add_argument(
1005 '-q', '--check-only',
1006 action='store_true',
1007 help='silently exit with 1 if files would be modified by meson format'
1008 )
1009 inplace_group.add_argument(
1010 '-d', '--check-diff',
1011 action='store_true',
1012 default=False,
1013 help='exit with 1 and show diff if files would be modified by meson format'
1014 )
1015 inplace_group.add_argument(
1016 '-i', '--inplace',
1017 action='store_true',
1018 help='format files in-place'
1019 )
1020 parser.add_argument(
1021 '-r', '--recursive',
1022 action='store_true',
1023 help='recurse subdirs (requires --check-only, --check-diff or --inplace option)',
1024 )
1025 parser.add_argument(
1026 '-s', '--subprojects',
1027 action='store_true',
1028 help='recurse subprojects (requires --recursive)',
1029 )
1030 parser.add_argument(
1031 '-c', '--configuration',
1032 metavar='meson.format',
1033 type=Path,
1034 help='read configuration from meson.format'
1035 )
1036 parser.add_argument(
1037 '-e', '--editor-config',
1038 action='store_true',
1039 default=False,
1040 help='try to read configuration from .editorconfig'
1041 )
1042 parser.add_argument(
1043 '-o', '--output',
1044 type=Path,
1045 help='output file (implies having exactly one input)'
1046 )
1047 parser.add_argument(
1048 '--source-file-path',
1049 type=Path,
1050 help='path to use, when reading from stdin'
1051 )
1052 parser.add_argument(
1053 'sources',
1054 nargs='*',
1055 type=Path,
1056 help='meson source files'
1057 )
1058
1059 def get_meson_format(sources: T.List[Path]) -> T.Optional[Path]:
1060 for src_file in sources:
1061 for parent in src_file.resolve().parents:
1062 target = parent / 'meson.format'
1063 if target.is_file():
1064 return target
1065 return None
1066
1067 def run(options: argparse.Namespace) -> int:
1068 if options.output and len(options.sources) != 1:
1069 raise MesonException('--output argument implies having exactly one source file')
1070 if options.recursive and not (options.inplace or options.check_only or options.check_diff):
1071 raise MesonException('--recursive argument requires one of --inplace, --check-diff or --check-only')
1072 if options.subprojects and not options.recursive:
1073 raise MesonException('--subprojects argument requires --recursive option')
1074
1075 from_stdin = len(options.sources) == 1 and options.sources[0].name == '-' and options.sources[0].parent == Path()
1076 if options.recursive and from_stdin:
1077 raise MesonException('--recursive argument is not compatible with stdin input')
1078 if options.inplace and from_stdin:
1079 raise MesonException('--inplace argument is not compatible with stdin input')
1080 if options.source_file_path and not from_stdin:
1081 raise MesonException('--source-file-path argument is only compatible with stdin input')
1082 if from_stdin and options.editor_config and not options.source_file_path:
1083 raise MesonException('using --editor-config with stdin input requires --source-file-path argument')
1084
1085 sources: T.List[Path] = options.sources.copy() or [Path(build_filename)]
1086
1087 if not options.configuration:
1088 options.configuration = get_meson_format(sources)
1089
1090 formatter = Formatter(options.configuration, options.editor_config, options.recursive, options.subprojects)
1091 err = 0
1092
1093 while sources:
1094 src_file = sources.pop(0)
1095 if src_file.is_dir():
1096 src_file = src_file / build_filename
1097
1098 try:
1099 if from_stdin:
1100 src_file = options.source_file_path or Path('STDIN') # used for error messages and introspection
1101 code = sys.stdin.read()
1102 else:
1103 code = src_file.read_text(encoding='utf-8')
1104 except IOError as e:
1105 raise MesonException(f'Unable to read from {src_file}') from e
1106
1107 formatted = formatter.format(code, src_file)
1108 if options.recursive:
1109 sources.extend(formatter.subdirs)
1110
1111 if options.inplace:
1112 try:
1113 with src_file.open('w', encoding='utf-8', newline=formatter.current_config.newline) as sf:
1114 sf.write(formatted)
1115 except IOError as e:
1116 raise MesonException(f'Unable to write to {src_file}') from e
1117 elif options.check_only or options.check_diff:
1118 if code != formatted:
1119 err = 1
1120 if options.check_diff:
1121 diff = difflib.unified_diff(code.splitlines(), formatted.splitlines(),
1122 str(src_file), str(src_file),
1123 '(original)', '(reformatted)',
1124 lineterm='')
1125 print('\n'.join(diff))
1126 else:
1127 break
1128 elif options.output:
1129 try:
1130 with options.output.open('w', encoding='utf-8', newline=formatter.current_config.newline) as of:
1131 of.write(formatted)
1132 except IOError as e:
1133 raise MesonException(f'Unable to write to {options.output}') from e
1134 else:
1135 print(formatted, end='')
1136
1137 return err
1138
1139 # TODO: remove empty newlines when more than N (2...)
1140 # TODO: magic comment to prevent formatting
1141 # TODO: split long lines on binary operators
1142 # TODO: align series of assignments
1143 # TODO: align comments
1144 # TODO: move comments on long lines
1145
1146 # Differences from muon format:
1147 # - By default, uses two spaces before comment, and added option for that
1148 # - Muon will mix CRLF and LF on Windows files...
1149 # - Support for end_of_line char
1150 # - Support for max_line_length, end_of_line, insert_final_newline, tab_width in .editorconfig
1151 # - Option to simplify string literals
1152 # - Option to recognize and parse meson.build in subdirs
1153 # - Correctly compute line length when using tabs
1154 # - By default, arguments in files() are sorted naturally
1155 # - Option to group '--arg', 'value' on same line in multiline arguments