Debian Codegraph @

sedparse.py

raw symbols SCIP
1 # sedparse
2 # GNU sed's parser translated from C to Python
3 # https://github.com/aureliojargas/sedparse
4 #
5 # HOW IT WORKS
6 #
7 # The original sed script can be specified via strings (option -e) or via files
8 # (option -f). The main functions to handle them are compile_string() and
9 # compile_file(), respectively. Both are entrypoints to prepare the input for
10 # the real parsing which occurs in compile_program().
11 #
12 # The parser reads the sed script character by character (see inchar()). The
13 # opposite function is savchar(), which goes back one character, when necessary.
14 # There are also some specialized input reading functions, for example
15 # in_integer() to read a sequence of integers and in_nonblank() to skip a
16 # sequence of white space chars.
17 #
18 # The normal flow is reading the chars forward with inchar() to detect the
19 # addresses, commands and their arguments. When the end of the current structure
20 # is only detected after reading the next char, which is not part of that
21 # structure (for example, getting any non number while reading integers in
22 # in_integer()), then savchar() is called to give that char back so the main
23 # parser will handle it.
24 #
25 # The data for every successfully parsed command is saved as an instance of the
26 # struct_sed_cmd class, which is appended in-place to the cur_program list,
27 # specified as an argument when calling compile_string() or compile_file().
28 #
29 # Any detected syntax error aborts the parsing immediately and a ParseError
30 # exception is raised (see bad_prog()).
31 #
32 # The code uses some global variables to save state:
33 #
34 # prog
35 #
36 # A class to hold information about the input script. If it is a file,
37 # `prog.file` will hold the open file descriptor (which during the parsing
38 # is read using fd.seek() and fd.tell()). If it the input came from a string
39 # (-e option), `prog.base`, `prog.cur` and `prog.end` will be used to save
40 # state about where the cursor is currently pointing in the string. See more
41 # details in the `prog_info` class comments.
42 #
43 # cur_input
44 #
45 # A class to keep information used in error messages. We have the script
46 # file name and line number saved in `cur_input.name` and `cur_input.line`,
47 # and if it's not a file, `cur_input.string_expr_count` holds the index of
48 # the command line "-e" expression.
49 #
50 # blocks
51 #
52 # An integer describing the current depth of the script. Any new block "{"
53 # adds a new depth level and its respective "}" remove a level. A script
54 # like "$ { /foo/ { p;};}" will have blocks=2 when reading the "p" command,
55 # but will become blocks=0 when reading the last "}".
56 #
57 # pending_text
58 # old_text_buf
59 #
60 # Those two variables are temporary data holders so the parser can
61 # "remember" data from the previous parsed script. This allows for scripts
62 # like "sed -e 'i\' -e foo", where a single "i" command is specified in two
63 # chunks (by using the -e option twice).
64
65 # STILL NOT TRANSLATED
66 # - Check if command only accepts one address
67 # if (cur_cmd->a2) bad_prog (_(ONE_ADDR))
68 # - Check POSIX compatibility (all GNU sed extensions are supported here)
69 # if (posixicity == POSIXLY_BASIC)
70
71 # Since sedparse is a literal translation, maintaining the same code, variables
72 # and method names, I have to disable the following checks.
73 # pylint: disable=global-statement
74 # pylint: disable=invalid-name
75 # pylint: disable=no-else-break
76 # pylint: disable=no-else-return
77 # pylint: disable=too-few-public-methods
78 # pylint: disable=too-many-branches
79 # pylint: disable=too-many-lines
80 # pylint: disable=too-many-statements
81
82 from __future__ import print_function # pylint: disable=unused-variable
83 import argparse
84 import json
85 import os
86 import sys
87 import tempfile
88
89 __version__ = "0.1.2"
90
91 # Adapt some C entities to Python
92 NULL = None
93 EOF = "<EOF>"
94
95 # Default options when dumping JSON
96 # The separators argument is required in python2 https://bugs.python.org/issue16333
97 JSON_OPTS = {"indent": 4, "sort_keys": True, "separators": (",", ": ")}
98
99
100 # Base class to handle translated C structs
101 class struct:
102 def to_dict(self, remove_empty=True):
103 """
104 Return the struct data as a dict.
105
106 Using plain self.__dict__ works only for a single level. This function
107 is recursive and converts all the nested structs.
108
109 When using remove_empty, keys that have empty or default values are removed.
110
111 Note that the structs use no dictionaries to store their data, so we
112 don't need to check for it in this code.
113 """
114 d = {}
115 for key, val in self.__dict__.items():
116 if isinstance(val, struct):
117 val = val.to_dict(remove_empty)
118 if remove_empty:
119 if val is None or val in ("", (), [], {}):
120 continue
121 if key == "int_arg" and val == -1:
122 continue
123 if key == "addr_bang" and not val:
124 continue
125 if key == "addr_step" and val == 0:
126 continue
127 if (
128 key == "addr_number"
129 and val == 0
130 and self.__dict__["addr_type"] in (ADDR_IS_REGEX, ADDR_IS_LAST)
131 ):
132 continue
133 d[key] = val
134 return d
135
136 def to_json(self, remove_empty=True):
137 return json.dumps(self, default=lambda x: x.to_dict(remove_empty), **JSON_OPTS)
138
139
140 class ParseError(Exception):
141 # pylint: disable=too-many-arguments
142 def __init__(self, message="", file="", line=0, column=0, expression=0, exitcode=1):
143 # https://stackoverflow.com/a/38857736
144 super(ParseError, self).__init__(message)
145 self.message = message
146 self.file = file
147 self.line = line
148 self.column = column
149 self.expression = expression
150 self.exitcode = exitcode
151
152
153 ######################################## translated from sed.c
154
155 program_name = "sedparse"
156
157 ######################################## translated from basicdefs.h
158
159
160 def ISBLANK(c):
161 return c in (" ", "\t")
162
163
164 def ISDIGIT(ch):
165 return ch in "0123456789"
166
167
168 def ISSPACE(c):
169 # https://github.com/gcc-mirror/gcc/blob/master/include/safe-ctype.h
170 return c in (" ", "\t", "\n", "\v", "\f", "\r")
171
172
173 ######################################## translated from sed.h
174
175 # The translation of the following was not necessary:
176 # - struct vector
177 # - enum replacement_types
178 # - enum text_types
179 # - enum posixicity_types
180 # - enum addr_state
181
182 # sedparse: The original code handles file open/read/write/close operations,
183 # but here we only care about the filename.
184 class struct_output(struct):
185 def __init__(self):
186 self.name = ""
187
188 # sedparse: not used
189 # missing_newline = False
190 # fp = None
191 # link = None
192
193 def __repr__(self):
194 return "%s(name=%r)" % (self.__class__.__name__, self.name)
195
196 def __str__(self):
197 return self.name
198
199
200 class struct_text_buf(struct):
201 def __init__(self):
202 self.text = []
203 # text_length = 0 # sedparse: not used
204
205 def __repr__(self):
206 return "%s(text=%r)" % (self.__class__.__name__, self.text)
207
208 def __str__(self):
209 return "".join(self.text)[:-1] # remove trailing \n
210
211
212 class struct_regex(struct):
213 def __init__(self):
214 self.pattern = ""
215
216 # In the original this was an integer, a bitwise OR for address flags.
217 # In sedparse it is a string with all the found flags, in their
218 # original order, and even repetition is preserved. It is also used
219 # to save both regex address flags and "s" command flags.
220 self.flags = "" # sedparse: was 0 in the original
221
222 # This is used to save the slash char used as delimiter in: regex
223 # addresses (/foo/p) and in "s" and "y" commands (s///).
224 self.slash = "" # sedparse extension
225
226 # sedparse: not used
227 # sz = 0
228 # dfa = None # struct_dfa()
229 # begline = False
230 # endline = False
231 # re = ""
232
233 def __repr__(self):
234 return "%s(slash=%r, pattern=%r, flags=%r)" % (
235 self.__class__.__name__,
236 self.slash,
237 self.pattern,
238 self.flags,
239 )
240
241 def __str__(self):
242 return self.escape() + self.slash + self.pattern + self.slash + self.flags
243
244 def escape(self): # sedparse extension
245 return "\\" if self.slash != "/" else ""
246
247
248 # enum addr_types
249 # fmt: off
250 ADDR_IS_NULL = 1 # null address
251 ADDR_IS_REGEX = 2 # a.addr_regex is valid
252 ADDR_IS_NUM = 3 # a.addr_number is valid
253 ADDR_IS_NUM_MOD = 4 # a.addr_number is valid, addr_step is modulo
254 ADDR_IS_STEP = 5 # address is +N (only valid for addr2)
255 ADDR_IS_STEP_MOD = 6 # address is ~N (only valid for addr2)
256 ADDR_IS_LAST = 7 # address is $
257 # fmt: on
258
259
260 class struct_addr(struct):
261 def __init__(self):
262 self.addr_type = ADDR_IS_NULL # enum addr_types
263 self.addr_number = 0
264 self.addr_step = 0
265 self.addr_regex = struct_regex()
266
267 def __repr__(self):
268 return "%s(addr_type=%r, addr_number=%r, addr_step=%r, addr_regex=%r)" % (
269 self.__class__.__name__,
270 self.addr_type,
271 self.addr_number,
272 self.addr_step,
273 self.addr_regex,
274 )
275
276 def __str__(self):
277 ret = ""
278 if self.addr_type == ADDR_IS_REGEX:
279 ret = str(self.addr_regex)
280 elif self.addr_type == ADDR_IS_NUM:
281 ret = str(self.addr_number)
282 elif self.addr_type == ADDR_IS_NUM_MOD:
283 ret = "%s~%s" % (self.addr_number, self.addr_step)
284 elif self.addr_type == ADDR_IS_STEP:
285 ret = "+%s" % self.addr_step
286 elif self.addr_type == ADDR_IS_STEP_MOD:
287 ret = "~%s" % self.addr_step
288 elif self.addr_type == ADDR_IS_LAST:
289 ret = "$"
290 else: # sedparse: this condition should not happen
291 ret = "<unknown address type '%s'>" % self.addr_type
292 return ret
293
294
295 class struct_replacement(struct):
296 def __init__(self):
297 self.text = "" # sedparse extension
298
299 # sedparse: not used
300 # prefix = ""
301 # prefix_length = 0
302 # subst_id = 0
303 # repl_type = REPL_ASIS # enum replacement_types
304 # next_ = None # struct_replacement
305
306 def __repr__(self):
307 return "%s(text=%r)" % (self.__class__.__name__, self.text)
308
309 def __str__(self):
310 return self.text
311
312
313 class struct_subst(struct):
314 def __init__(self):
315 self.regx = struct_regex()
316 self.replacement = struct_replacement()
317 self.outf = struct_output() # "w" option given
318
319 # sedparse: not used
320 # Note that instead of using those attributes to save the found flags,
321 # sedparse saves them to self.regx.flags as a single string, preserving
322 # the original order and possible repetition.
323 # numb = 0 # if >0, only substitute for match number "numb"
324 # global_ = False # "g" option given
325 # print_ = False # "p" option given (before/after eval)
326 # eval_ = False # "e" option given
327 # max_id = 0 # maximum backreference on the RHS
328 # replacement_buffer = "" # ifdef lint
329
330 def __repr__(self):
331 return "%s(regx=%r, replacement=%r, outf=%r)" % (
332 self.__class__.__name__,
333 self.regx,
334 self.replacement,
335 self.outf,
336 )
337
338 def __str__(self):
339 return (
340 self.regx.slash
341 + str(self.regx.pattern)
342 + self.regx.slash
343 + str(self.replacement.text)
344 + self.regx.slash
345 + self.regx.flags
346 + (" " + self.outf.name if "w" in self.regx.flags else "")
347 )
348
349
350 # sedparse: In the original this was a 'union' inside 'struct sed_cmd'
351 class struct_sed_cmd_x(struct):
352 "auxiliary data for various commands"
353
354 def __init__(self):
355 # This structure is used for a, i, and c commands.
356 self.cmd_txt = struct_text_buf()
357
358 # This is used for the l, q and Q commands.
359 self.int_arg = -1
360
361 # This is used for the r command. (sedparse: and R w W)
362 self.fname = ""
363
364 # This is used for the hairy s command. (sedparse: and y)
365 self.cmd_subst = struct_subst()
366
367 # This is used for the ":" command.
368 self.label_name = ""
369
370 # This is used for the command comment.
371 self.comment = "" # sedparse extension
372
373 # sedparse: not used
374 # # This is used for the {}, b, and t commands.
375 # jump_index = 0
376 # # This is used for the w command.
377 # outf = struct_output()
378 # # This is used for the R command.
379 # # (despite the struct name, it is used for both in and out files).
380 # inf = struct_output()
381 # # This is used for the y command.
382 # translate = ""
383 # translatemb = ""
384
385 def __repr__(self):
386 return (
387 "%s(int_arg=%r, label_name=%r, fname=%r, comment=%r,"
388 " cmd_txt=%r, cmd_subst=%r)"
389 % (
390 self.__class__.__name__,
391 self.int_arg,
392 self.label_name,
393 self.fname,
394 self.comment,
395 self.cmd_txt,
396 self.cmd_subst,
397 )
398 )
399
400
401 class struct_sed_cmd(struct):
402 def __init__(self):
403 # Command addresses
404 self.a1 = struct_addr()
405 self.a2 = struct_addr()
406
407 # Non-zero if command is to be applied to non-matches.
408 self.addr_bang = False # sedparse: using bool
409
410 # The actual command character.
411 self.cmd = ""
412
413 # auxiliary data for various commands
414 self.x = struct_sed_cmd_x()
415
416 # The original line number where this command was found
417 self.line = 0 # sedparse extension
418
419 # sedparse: not used
420 # range_state = RANGE_INACTIVE # See enum addr_state
421
422 def __repr__(self):
423 return "%s(line=%r, cmd=%r, addr_bang=%r, a1=%r, a2=%r, x=%r)" % (
424 self.__class__.__name__,
425 self.line,
426 self.cmd,
427 self.addr_bang,
428 self.a1,
429 self.a2,
430 self.x,
431 )
432
433 def __str__(self):
434 ret = []
435
436 if self.a1:
437 ret.append(str(self.a1))
438 if self.a2:
439 ret.append(",%s" % self.a2)
440 if ret:
441 ret.append(" ")
442
443 if self.addr_bang:
444 ret.append("!")
445
446 ret.append(self.cmd)
447
448 if self.cmd == "\n":
449 pass
450 elif self.cmd == "#":
451 ret.append(self.x.comment)
452 elif self.cmd == ":":
453 ret.append(self.x.label_name)
454 elif self.cmd in ("s", "y"):
455 ret.append(str(self.x.cmd_subst))
456 elif self.x.label_name:
457 ret.append(" " + self.x.label_name)
458 elif self.x.fname:
459 ret.append(" " + self.x.fname)
460 elif self.x.int_arg > -1:
461 ret.append(" %s" % self.x.int_arg)
462 elif self.x.cmd_txt.text: # a i c
463 ret.append("\\\n%s" % self.x.cmd_txt)
464
465 return "".join(ret)
466
467
468 # This is defined in sed.h, but calls is_mb_char() from mbcs.c, where the real
469 # implementation is.
470 # XXX sedparse: maybe the translation is wrong or incomplete. It seems to work,
471 # but I'm not sure if there are some unhandled edge cases here.
472 def IS_MB_CHAR(ch):
473 """Return True if ch is EOF or a valid single-byte character"""
474 # sedparse: the first condition is necessary because our EOF constant is a
475 # string.
476 return ch != EOF and ord(ch) > 127
477
478
479 ######################################## translated from regexp.c
480
481 # sedparse: no need to compile the regex, just save the collected strings
482 def compile_regex(pattern, flags):
483 r = struct_regex()
484 r.pattern = "".join(pattern)
485 r.flags = "".join(flags)
486 return r
487
488
489 ######################################## translated from utils.h
490
491 # enum exit_codes
492 EXIT_SUCCESS = 0
493 EXIT_BAD_USAGE = 1 # bad program syntax, invalid command-line options
494 # EXIT_BAD_INPUT = 2 # failed to open some of the input files (sedparse: not used)
495 EXIT_PANIC = 4 # PANIC during program execution
496
497 ######################################## translated from utils.c
498
499 # Print an error message and exit
500 def panic(msg):
501 raise ParseError(exitcode=EXIT_PANIC, message="%s: %s" % (program_name, msg))
502
503
504 # In Python we have lists, so all the buffer-related C code is not necessary.
505 # Only the very minimal set of buffer functions were translated, to avoid having
506 # to change the logic in the caller code.
507
508
509 def init_buffer():
510 return []
511
512
513 def add1_buffer(buffer, ch):
514 if ch != EOF:
515 buffer.append(ch) # in-place
516 # the return is never used
517
518
519 def free_buffer(b):
520 del b
521
522
523 ######################################## translated from compile.c
524
525 OPEN_BRACKET = "["
526 CLOSE_BRACKET = "]"
527 CLOSE_BRACE = "}"
528
529
530 class prog_info:
531 # When we're reading a script command from a string, `prog.base' points to
532 # the first character in the string, 'prog.cur' points to the current
533 # character in the string, and 'prog.end' points to the end of the string.
534 # This allows us to compile script strings that contain nulls.
535 base = None # int
536 cur = None # int
537 end = None # int
538
539 # This is the current script file. If it is NULL, we are reading from a
540 # string stored at `prog.cur' instead. If both `prog.file' and `prog.cur'
541 # are NULL, we're in trouble!
542 file = None # file descriptor
543
544 # Using None because some code checks for "is not None" to detect unset state
545 text = None # sedparse extension
546
547
548 class error_info:
549 """Information used to give out useful and informative error messages."""
550
551 # This is the name of the current script file.
552 name = ""
553
554 # This is the number of the current script line that we're compiling.
555 line = 0
556
557 # This is the index of the "-e" expressions on the command line.
558 string_expr_count = 0
559
560
561 # Where we are in the processing of the input.
562 class prog(prog_info):
563 pass
564
565
566 class cur_input(error_info):
567 pass
568
569
570 # Allow for scripts like "sed -e 'i\' -e foo"
571 pending_text = NULL
572 old_text_buf = NULL
573
574 # sedparse: this is a sed_label struct in the original code. Here it is just an
575 # integer, because we only care about the indenting levels.
576 blocks = 0
577
578 # Various error messages we may want to print
579 # sedparse: not used messages are commented
580 BAD_BANG = "multiple `!'s"
581 BAD_COMMA = "unexpected `,'"
582 BAD_STEP = "invalid usage of +N or ~N as first address"
583 EXCESS_OPEN_BRACE = "unmatched `{'"
584 EXCESS_CLOSE_BRACE = "unexpected `}'"
585 EXCESS_JUNK = "extra characters after command"
586 EXPECTED_SLASH = "expected \\ after `a', `c' or `i'"
587 NO_CLOSE_BRACE_ADDR = "`}' doesn't want any addresses"
588 # NO_COLON_ADDR = ": doesn't want any addresses"
589 # NO_SHARP_ADDR = "comments don't accept any addresses"
590 NO_COMMAND = "missing command"
591 # ONE_ADDR = "command only uses one address"
592 UNTERM_ADDR_RE = "unterminated address regex"
593 UNTERM_S_CMD = "unterminated `s' command"
594 UNTERM_Y_CMD = "unterminated `y' command"
595 UNKNOWN_S_OPT = "unknown option to `s'"
596 EXCESS_P_OPT = "multiple `p' options to `s' command"
597 EXCESS_G_OPT = "multiple `g' options to `s' command"
598 EXCESS_N_OPT = "multiple number options to `s' command"
599 ZERO_N_OPT = "number option to `s' command may not be zero"
600 # Y_CMD_LEN = "strings for `y' command are different lengths"
601 BAD_DELIM = "delimiter character is not a single-byte character"
602 # ANCIENT_VERSION = "expected newer version of sed"
603 INVALID_LINE_0 = "invalid usage of line address 0"
604 UNKNOWN_CMD = "unknown command: `%c'"
605 # INCOMPLETE_CMD = "incomplete command"
606 COLON_LACKS_LABEL = '":" lacks a label'
607 # RECURSIVE_ESCAPE_C = "recursive escaping after \\c not allowed"
608 # DISALLOWED_CMD = "e/r/w commands disabled in sandbox mode"
609 MISSING_FILENAME = "missing filename in r/R/w/W commands"
610
611 # Complain about an unknown command and exit.
612 def bad_command(ch):
613 bad_prog(UNKNOWN_CMD % ch)
614
615
616 # Complain about a programming error and exit.
617 def bad_prog(why):
618 if cur_input.name:
619 msg = "%s: file %s line %d: %s" % (
620 program_name,
621 cur_input.name,
622 cur_input.line,
623 why,
624 )
625 else:
626 msg = "%s: -e expression #%d, char %d: %s" % (
627 program_name,
628 cur_input.string_expr_count,
629 (prog.cur or 0) - (prog.base or 0),
630 why,
631 )
632
633 # sedparse extension
634 # The following exception can be caught and this module can be used again.
635 # Reset to make sure data from one execution won't affect the next.
636 reset_globals()
637
638 # sedparse extension
639 # In this point, the original code shows the error message and exits. Doing
640 # it here would break the usage of sedparse as a Python module. So we raise
641 # an exception instead, and the calling code decides what to do.
642 raise ParseError(
643 message=msg,
644 file=cur_input.name,
645 expression=cur_input.string_expr_count,
646 line=cur_input.line,
647 column=(prog.cur - prog.base) if prog.cur else 0,
648 exitcode=EXIT_BAD_USAGE,
649 )
650
651
652 # Read the next character from the program. Return EOF if there isn't anything
653 # to read. Keep cur_input.line up to date, so error messages can be meaningful.
654 def inchar():
655 ch = EOF
656 if prog.cur is not None:
657 if prog.cur < prog.end:
658 # Original: ch = *prog.cur++;
659 ch = prog.text[prog.cur]
660 prog.cur += 1
661 elif prog.file:
662 # Original: if (!feof (prog.file)) ch = getc (prog.file);
663 # https://stackoverflow.com/a/15599780
664 ch = prog.file.read(1)
665 if not ch:
666 ch = EOF
667 if ch == "\n":
668 cur_input.line += 1
669 debug(ch, stats=True)
670 return ch
671
672
673 # unget `ch' so the next call to inchar will return it.
674 def savchar(ch):
675 debug("savchar(%s)" % ch, stats=True)
676 if ch == EOF:
677 return
678 if ch == "\n" and cur_input.line > 0:
679 cur_input.line -= 1
680 if prog.cur:
681 # Original: if (prog.cur <= prog.base || *--prog.cur != ch)
682 prog.cur -= 1
683 if prog.cur <= prog.base or prog.text[prog.cur] != ch:
684 panic(
685 # sedparse: original code only shows `ch` in this error message
686 "Called savchar with unexpected pushback (curr=%s %s!=%s)"
687 % (prog.cur, prog.text[prog.cur], ch)
688 )
689 else:
690 # Original: ungetc(ch, prog.file)
691 try:
692 # Go back one *character* in prog.file file descriptor pointer.
693 # Since one Unicode character can be composed of multiple bytes,
694 # we need that encoding to know how many bytes we should rewind.
695 # Note that tell() does not work when reading from STDIN, see
696 # the temporary file workaround in compile_file().
697 prog.file.seek(prog.file.tell() - len(ch.encode("utf-8")))
698 except ValueError: # negative seek position -1
699 pass
700
701
702 # Read the next non-blank character from the program.
703 def in_nonblank():
704 while True:
705 ch = inchar()
706 if not ISBLANK(ch):
707 break
708 return ch
709
710
711 # sedparse extension
712 # Ignore multiple trailing blanks and ; until EOC/EOL/EOF. Skipping those chars
713 # avoids \n incorrectly being considered a new command and producing a new
714 # undesired blank line in the output.
715 def ignore_trailing_fluff():
716 while True:
717 ch = in_nonblank()
718 if ch == ";": # skip it
719 pass
720 elif ch in (EOF, "\n"): # EOF, EOL
721 return
722 else: # start of a new command
723 savchar(ch)
724 return
725
726
727 # Consume script input until a valid end of command marker is found: comment,
728 # closing brace, newline, semicolon or EOF. If any other character is found, die
729 # with 'extra characters after command' error.
730 def read_end_of_cmd():
731 ch = in_nonblank()
732 if ch in (CLOSE_BRACE, "#"):
733 savchar(ch)
734 elif ch not in (EOF, "\n", ";"):
735 bad_prog(EXCESS_JUNK)
736
737 # sedparse extension: Ignore trailing blanks and ; until EOC/EOL/EOF
738 elif ch == ";":
739 ignore_trailing_fluff()
740
741
742 # Read an integer value from the program.
743 # sedparse: original code uses math, we use list append.
744 def in_integer(ch):
745 num = []
746 while ISDIGIT(ch):
747 num.append(ch)
748 ch = inchar()
749 savchar(ch)
750 return int("".join(num))
751
752
753 def add_then_next(buffer, ch):
754 add1_buffer(buffer, ch)
755 return inchar()
756
757
758 # convert_number() - Translation not needed
759
760 # sedparse extension
761 # This is a copy of read_filename, but preserving blanks.
762 def read_comment():
763 b = init_buffer()
764 ch = inchar()
765 while ch not in (EOF, "\n"):
766 ch = add_then_next(b, ch)
767 return b
768
769
770 # Read in a filename for a `r', `w', or `s///w' command.
771 def read_filename():
772 b = init_buffer()
773 ch = in_nonblank()
774 while ch not in (EOF, "\n"):
775 ch = add_then_next(b, ch)
776 # add1_buffer(b, "\0"); # not necessary in Python
777 return b
778
779
780 # get_openfile() - Translation not needed
781
782
783 def next_cmd_entry(vector):
784 # sedparse: in the original there's some of vector handling code. Here the
785 # equivalent is the next line and `vector.append()` at the end.
786 cmd = struct_sed_cmd()
787 cmd.a1 = NULL
788 cmd.a2 = NULL
789 # cmd.range_state = RANGE_INACTIVE # sedparse: not used
790 cmd.addr_bang = False
791 cmd.cmd = "\0" # something invalid, to catch bugs early
792 vector.append(cmd)
793 return cmd
794
795
796 def snarf_char_class(b): # sedparse: cur_stat argument not necessary
797 state = 0
798 delim = None # delim IF_LINT( = 0)
799
800 ch = inchar()
801 if ch == "^":
802 ch = add_then_next(b, ch)
803 if ch == CLOSE_BRACKET:
804 ch = add_then_next(b, ch)
805
806 # States are:
807 # 0 outside a collation element, character class or collation class
808 # 1 after the bracket
809 # 2 after the opening ./:/=
810 # 3 after the closing ./:/=
811
812 # Original: for (;; ch = add_then_next(b, ch)) {
813 first_loop_run = True
814 while True:
815 if not first_loop_run:
816 ch = add_then_next(b, ch)
817 first_loop_run = False
818
819 mb_char = IS_MB_CHAR(ch)
820
821 if ch in (EOF, "\n"):
822 return ch
823
824 if ch in (".", ":", "="):
825 if mb_char:
826 continue
827
828 if state == 1:
829 delim = ch
830 state = 2
831 elif state == 2 and ch == delim:
832 state = 3
833 # else:
834 # break # break from C-switch not necessary in Python
835
836 continue
837
838 if ch == OPEN_BRACKET:
839 if mb_char:
840 continue
841
842 if state == 0:
843 state = 1
844 continue
845
846 if ch == CLOSE_BRACKET:
847 if mb_char:
848 continue
849
850 if state in (0, 1):
851 return ch
852
853 if state == 3:
854 state = 0
855
856 # Getting a character different from .=: whilst in state 1
857 # goes back to state 0, getting a character different from ]
858 # whilst in state 3 goes back to state 2.
859 #
860 # Original: state &= ~1
861 # sedparse: Instead of following the original (tricky &= right after a
862 # switch inside a loop), I've opted to implement literally what the
863 # comment says.
864 if ch not in (".", ":", "=") and state == 1:
865 state = 0
866 elif ch != CLOSE_BRACKET and state == 3:
867 state = 2
868
869
870 def match_slash(slash, regex): # char, bool
871 # We allow only 1 byte characters for a slash.
872 if IS_MB_CHAR(slash):
873 bad_prog(BAD_DELIM)
874
875 b = init_buffer()
876
877 # Original: while ((ch = inchar ()) != EOF && ch != '\n')
878 while True:
879 ch = inchar()
880 if ch in (EOF, "\n"):
881 break
882
883 if not IS_MB_CHAR(ch):
884 if ch == slash:
885 return b
886
887 elif ch == "\\":
888 ch = inchar()
889 if ch == EOF:
890 break
891
892 # sedparse: GNU sed interprets \n here, we don't
893 # elif ch == "n" and regex:
894 # ch = "\n"
895
896 # sedparse: GNU sed remove the leading \ from \\n, \/, \&.
897 # We don't since we keep the original user text.
898 # elif (ch != "\n" and (ch != slash or (not regex and ch == "&"))):
899 else:
900 add1_buffer(b, "\\")
901
902 elif ch == OPEN_BRACKET and regex:
903 add1_buffer(b, ch)
904 ch = snarf_char_class(b)
905 if ch != CLOSE_BRACKET:
906 break
907
908 add1_buffer(b, ch)
909
910 if ch == "\n":
911 savchar(ch) # for proper line number in error report
912 free_buffer(b)
913 return NULL
914
915
916 # sedparse: this function works differently from the original.
917 # In GNU sed, there's no return, since it just sets all the flags as properties
918 # of "cmd_s". Here it collects and returns the flags as a list.
919 def mark_subst_opts(cmd_s):
920 flags = []
921 numb = False
922
923 while True:
924 ch = in_nonblank()
925 debug("s flag candidate: %r" % ch)
926
927 # sedparse: just append the flags to the list
928 if ch in ("i", "I", "m", "M", "e"): # GNU extensions
929 flags.append(ch)
930
931 elif ch == "p":
932 if ch in flags:
933 bad_prog(EXCESS_P_OPT)
934 flags.append(ch)
935
936 elif ch == "g":
937 if ch in flags:
938 bad_prog(EXCESS_G_OPT)
939 flags.append(ch)
940
941 elif ch == "w":
942 flags.append(ch)
943 # sedparse: This flag will always be at the end of the list, since
944 # after w cannot exist any other flag because the filename consumes
945 # everything until the end of the line.
946 b = read_filename()
947 if not b:
948 bad_prog(MISSING_FILENAME)
949 cmd_s.outf.name = "".join(b)
950 debug("s flag filename: %r" % cmd_s.outf.name)
951 return flags
952
953 elif ch in "0123456789":
954 if numb:
955 bad_prog(EXCESS_N_OPT)
956 n = in_integer(ch)
957 if int(n) == 0:
958 bad_prog(ZERO_N_OPT)
959 flags.append(str(n))
960 numb = True
961
962 elif ch in (CLOSE_BRACE, "#"):
963 savchar(ch)
964 return flags
965
966 elif ch in (EOF, "\n"):
967 return flags
968
969 # sedparse extension: Ignore trailing blanks and ; until EOC/EOL/EOF
970 elif ch == ";":
971 ignore_trailing_fluff()
972 return flags
973
974 elif ch == "\r":
975 if inchar() == "\n":
976 return flags
977 bad_prog(UNKNOWN_S_OPT)
978
979 else:
980 bad_prog(UNKNOWN_S_OPT)
981
982
983 # read in a label for a `:', `b', or `t' command
984 def read_label():
985 b = init_buffer()
986 ch = in_nonblank()
987
988 while ch not in (EOF, "\n", ";", CLOSE_BRACE, "#") and not ISBLANK(ch):
989 ch = add_then_next(b, ch)
990
991 savchar(ch)
992
993 # sedparse extension: Ignore trailing blanks and ; until EOC/EOL/EOF
994 ignore_trailing_fluff()
995
996 # add1_buffer(b, "\0") # not necessary in Python
997 ret = "".join(b)
998 free_buffer(b)
999 return ret
1000
1001
1002 # setup_label() - Translation not needed
1003 # release_label() - Translation not needed
1004 # new_replacement() - Translation not needed
1005 # setup_replacement() - Translation not needed
1006
1007
1008 def read_text(buf, leadin_ch):
1009 global pending_text
1010 global old_text_buf
1011
1012 # Should we start afresh (as opposed to continue a partial text)?
1013 if buf:
1014 if pending_text:
1015 free_buffer(pending_text)
1016 pending_text = init_buffer()
1017 buf.text = []
1018 old_text_buf = buf
1019
1020 if leadin_ch == EOF:
1021 return
1022
1023 if leadin_ch != "\n":
1024 add1_buffer(pending_text, leadin_ch)
1025
1026 ch = inchar()
1027 while ch not in (EOF, "\n"):
1028 if ch == "\\":
1029 ch = inchar()
1030 if ch != EOF:
1031 add1_buffer(pending_text, "\\")
1032
1033 if ch == EOF:
1034 add1_buffer(pending_text, "\n")
1035 return
1036
1037 ch = add_then_next(pending_text, ch)
1038
1039 add1_buffer(pending_text, "\n")
1040
1041 if not buf:
1042 buf = old_text_buf
1043 buf.text = pending_text[:]
1044 free_buffer(pending_text)
1045 pending_text = NULL
1046
1047
1048 # Try to read an address for a sed command. If it succeeds, return non-zero and
1049 # store the resulting address in `*addr'. If the input doesn't look like an
1050 # address read nothing and return zero.
1051 def compile_address(addr, ch): # struct_addr, str
1052 addr.addr_type = ADDR_IS_NULL
1053 addr.addr_step = 0
1054 addr.addr_number = 0 # extremely unlikely to ever match
1055 addr.addr_regex = NULL
1056
1057 if ch in ("/", "\\"):
1058 # sedparse: Instead of using bit flags as in regex.c, we just save the
1059 # flags into a list
1060 flags = []
1061 addr.addr_type = ADDR_IS_REGEX
1062 if ch == "\\":
1063 ch = inchar()
1064 b = match_slash(ch, True)
1065 if b == NULL:
1066 bad_prog(UNTERM_ADDR_RE)
1067 # sedparse extension: we save the slash char
1068 slash = ch
1069
1070 while True:
1071 ch = in_nonblank()
1072 # if posixicity == POSIXLY_BASIC:
1073 # goto posix_address_modifier
1074 if ch == "I": # GNU extension
1075 flags.append(ch)
1076 elif ch == "M": # GNU extension
1077 flags.append(ch)
1078 else:
1079 # posix_address_modifier: # GOTO label
1080 savchar(ch)
1081 addr.addr_regex = compile_regex(b, flags)
1082 addr.addr_regex.slash = slash
1083 free_buffer(b)
1084 return True
1085
1086 elif ISDIGIT(ch):
1087 addr.addr_number = in_integer(ch)
1088 addr.addr_type = ADDR_IS_NUM
1089 ch = in_nonblank()
1090 if ch != "~": # or posixicity == POSIXLY_BASIC:
1091 savchar(ch)
1092 else:
1093 step = in_integer(in_nonblank())
1094 if step > 0:
1095 addr.addr_step = step
1096 addr.addr_type = ADDR_IS_NUM_MOD
1097
1098 elif ch in ("+", "~"): # and posixicity != POSIXLY_BASIC:
1099 addr.addr_step = in_integer(in_nonblank())
1100 # sedparse: skipping this to match and save 1,~0p and 1,+0p
1101 # if addr.addr_step == 0:
1102 # pass # default to ADDR_IS_NULL; forces matching to stop on next line
1103 # elif ch == "+":
1104 if ch == "+":
1105 addr.addr_type = ADDR_IS_STEP
1106 else:
1107 addr.addr_type = ADDR_IS_STEP_MOD
1108
1109 elif ch == "$":
1110 addr.addr_type = ADDR_IS_LAST
1111
1112 else:
1113 return False
1114 return True
1115
1116
1117 # Read a program in and store the compiled form in `vector'.
1118 # Original:
1119 # Read a program (or a subprogram within `{' `}' pairs) in and store the
1120 # compiled form in `*vector'. Return a pointer to the new vector.
1121 def compile_program(vector):
1122 global blocks
1123
1124 if pending_text:
1125 read_text(NULL, "\n")
1126
1127 while True:
1128
1129 a = struct_addr()
1130
1131 # while ((ch=inchar ()) == ';' || ISSPACE (ch))
1132 # ;
1133 # if (ch == EOF)
1134 # break;
1135 while True:
1136 ch = inchar()
1137
1138 # sedparse extension:
1139 # GNU sed parser discards the \n used as command separator.
1140 # Sedsed keeps all cosmetic line breaks (i.e. \n\n) when formatting
1141 # code. So here sedparse creates the concept of the \n command, to
1142 # identify and preserve those breaks.
1143 if ch == "\n":
1144 break
1145
1146 if ch != ";" and not ISSPACE(ch):
1147 break
1148
1149 if ch == EOF:
1150 break
1151
1152 cur_cmd = next_cmd_entry(vector)
1153 cur_cmd.line = cur_input.line # sedparse extension
1154
1155 if compile_address(a, ch):
1156 if a.addr_type == ADDR_IS_STEP or a.addr_type == ADDR_IS_STEP_MOD:
1157 bad_prog(BAD_STEP)
1158
1159 cur_cmd.a1 = a
1160 debug("----- Found address 1: %r" % cur_cmd.a1)
1161 a = struct_addr() # reset a
1162
1163 ch = in_nonblank()
1164 if ch == ",":
1165 if not compile_address(a, in_nonblank()):
1166 bad_prog(BAD_COMMA)
1167
1168 cur_cmd.a2 = a
1169 debug("----- Found address 2: %r" % cur_cmd.a2)
1170 ch = in_nonblank()
1171
1172 # sedparse: removed: or posixicity == POSIXLY_BASIC)):
1173 if cur_cmd.a1.addr_type == ADDR_IS_NUM and cur_cmd.a1.addr_number == 0:
1174 if not cur_cmd.a2 or cur_cmd.a2.addr_type != ADDR_IS_REGEX:
1175 bad_prog(INVALID_LINE_0)
1176
1177 if ch == "!":
1178 cur_cmd.addr_bang = True
1179 debug("----- Found negation: !")
1180 ch = in_nonblank()
1181 if ch == "!":
1182 bad_prog(BAD_BANG)
1183
1184 # Do not accept extended commands in --posix mode. Also,
1185 # a few commands only accept one address in that mode.
1186 # sedparse: SKIPPED
1187
1188 cur_cmd.cmd = ch
1189 debug("----- Found command: %r" % ch)
1190
1191 # sedparse extension
1192 if ch == "\n":
1193 # Adjust the line number for the empty lines, because they're just
1194 # detected in the next line
1195 cur_cmd.line -= 1
1196
1197 # Detect cases like 1\n, an address with no "real" command
1198 if cur_cmd.a1:
1199 bad_prog(NO_COMMAND)
1200
1201 elif ch == "#":
1202 # if (cur_cmd->a1)
1203 # bad_prog (_(NO_SHARP_ADDR));
1204
1205 # sedparse: no #n detection, it will be considered a normal comment.
1206 # It's up to the caller code to decide if this should be special.
1207
1208 # sedparse: GNU sed discards the comment contents, but we must save it
1209 # while ch != EOF and ch != "\n":
1210 # ch = inchar()
1211 # continue
1212 b = read_comment()
1213 cur_cmd.x.comment = "".join(b)
1214 debug("comment: %r" % cur_cmd.x.comment)
1215 free_buffer(b)
1216
1217 # sedparse: we just save the "v" command contents, no processing
1218 elif ch == "v":
1219 # sedparse extension: using label_name to store "v" argument
1220 cur_cmd.x.label_name = read_label()
1221 debug("argument: %s" % cur_cmd.x.label_name)
1222
1223 elif ch == "{":
1224 blocks += 1
1225
1226 # sedparse extension: Ignore trailing blanks and ; until EOC/EOL/EOF
1227 ignore_trailing_fluff()
1228
1229 # cur_cmd.addr_bang = not cur_cmd.addr_bang # ?
1230
1231 elif ch == "}":
1232 if not blocks:
1233 bad_prog(EXCESS_CLOSE_BRACE)
1234 if cur_cmd.a1:
1235 bad_prog(NO_CLOSE_BRACE_ADDR)
1236
1237 read_end_of_cmd()
1238 blocks -= 1 # done with this entry
1239
1240 # sedparse: "e" handling was moved here (original code uses GOTO)
1241 elif ch in ("a", "i", "c", "e"):
1242 ch = in_nonblank()
1243
1244 # sedparse: Empty "e" at EOF is allowed
1245 if ch == EOF and cur_cmd.cmd == "e":
1246 break
1247
1248 if ch == EOF:
1249 bad_prog(EXPECTED_SLASH)
1250
1251 if ch == "\\":
1252 ch = inchar()
1253 else:
1254 # if posixicity == POSIXLY_BASIC:
1255 # bad_prog(EXPECTED_SLASH)
1256 savchar(ch)
1257 ch = "\n"
1258
1259 read_text(cur_cmd.x.cmd_txt, ch)
1260 debug("text: %r" % cur_cmd.x.cmd_txt)
1261
1262 elif ch in (":", "T", "b", "t"):
1263 # if (cur_cmd->a1)
1264 # bad_prog (_(NO_COLON_ADDR));
1265 label = read_label()
1266 if ch == ":" and not label:
1267 bad_prog(COLON_LACKS_LABEL)
1268 cur_cmd.x.label_name = label
1269 debug("label: %r" % cur_cmd.x.label_name)
1270
1271 # The "L" command was added in GNU sed v3.95 (Oct 2002) and was removed
1272 # in v4.3 (Dec 2016). It used to format paragraphs like the "fmt" Unix
1273 # command does and accepted an optional integer argument. In those 14
1274 # years present in GNU sed, many users could have written scripts using
1275 # it, so sedparse will keep supporting this command.
1276 elif ch in ("Q", "q", "L", "l"):
1277 # if ch in ("Q", "q") and cur_cmd.a2:
1278 # bad_prog(ONE_ADDR)
1279 ch = in_nonblank()
1280 if ISDIGIT(ch): # and posixicity != POSIXLY_BASIC
1281 cur_cmd.x.int_arg = in_integer(ch)
1282 debug("int_arg: %r" % cur_cmd.x.int_arg)
1283 else:
1284 cur_cmd.x.int_arg = -1
1285 debug("int_arg: -1")
1286 savchar(ch)
1287 read_end_of_cmd()
1288
1289 elif ch in (
1290 "=",
1291 "d",
1292 "D",
1293 "F",
1294 "g",
1295 "G",
1296 "h",
1297 "H",
1298 "n",
1299 "N",
1300 "p",
1301 "P",
1302 "z",
1303 "x",
1304 ):
1305 read_end_of_cmd()
1306
1307 # sedparse: we just read the filename, nothing else
1308 elif ch in ("r", "R", "w", "W"):
1309 b = read_filename()
1310 if not b:
1311 bad_prog(MISSING_FILENAME)
1312 cur_cmd.x.fname = "".join(b)
1313 debug("filename: %r" % cur_cmd.x.fname)
1314 free_buffer(b)
1315
1316 elif ch == "s":
1317 slash = inchar()
1318
1319 b = match_slash(slash, True)
1320 if b == NULL:
1321 bad_prog(UNTERM_S_CMD)
1322 # sedparse extension: we save the slash and the pattern
1323 cur_cmd.x.cmd_subst.regx.slash = slash
1324 cur_cmd.x.cmd_subst.regx.pattern = "".join(b)
1325 debug("s pattern: %r" % cur_cmd.x.cmd_subst.regx.pattern)
1326 free_buffer(b) # sedparse: freeing earlier than in original code
1327
1328 b2 = match_slash(slash, False)
1329 if b2 == NULL:
1330 bad_prog(UNTERM_S_CMD)
1331 # sedparse: we just save the replacement text
1332 cur_cmd.x.cmd_subst.replacement.text = "".join(b2)
1333 debug("s replacement: %r" % cur_cmd.x.cmd_subst.replacement.text)
1334 free_buffer(b2)
1335
1336 # sedparse: here GNU compiles the regex, we just save the flags
1337 flags = "".join(mark_subst_opts(cur_cmd.x.cmd_subst))
1338 cur_cmd.x.cmd_subst.regx.flags = flags
1339 debug("s flags: %r" % cur_cmd.x.cmd_subst.regx.flags)
1340
1341 # if cur_cmd.x.cmd_subst.eval and sandbox:
1342 # bad_prog(_(DISALLOWED_CMD))
1343
1344 elif ch == "y":
1345 # sedparse extension: original code uses cur_cmd.x.translate and
1346 # cur_cmd.x.translatemb to save the translation tables for "y". We
1347 # instead, overload cur_cmd.x.cmd_subst to save the "y" unprocessed
1348 # data.
1349 slash = inchar()
1350 b = match_slash(slash, False)
1351 if b == NULL:
1352 bad_prog(UNTERM_Y_CMD)
1353 # sedparse extension: we save the slash and the pattern
1354 cur_cmd.x.cmd_subst.regx.slash = slash
1355 cur_cmd.x.cmd_subst.regx.pattern = "".join(b)
1356 debug("y pattern: %r" % cur_cmd.x.cmd_subst.regx.pattern)
1357
1358 b2 = match_slash(slash, False)
1359 if b2 == NULL:
1360 bad_prog(UNTERM_Y_CMD)
1361 # sedparse: we just save the replacement text
1362 cur_cmd.x.cmd_subst.replacement.text = "".join(b2)
1363 debug("y replacement: %r" % cur_cmd.x.cmd_subst.replacement.text)
1364
1365 # sedparse: Since we do not perform the de-escaping of \/, \\ and \\n
1366 # (see match_slash()), the length check is turned off.
1367 #
1368 # if len(normalize_text(b)) != len(normalize_text(b2)):
1369 # bad_prog(Y_CMD_LEN)
1370
1371 read_end_of_cmd()
1372 free_buffer(b)
1373 free_buffer(b2)
1374
1375 elif ch == EOF:
1376 bad_prog(NO_COMMAND)
1377 # /*NOTREACHED*/
1378 else:
1379 bad_command(ch)
1380 # /*NOTREACHED*/
1381
1382 # if posixicity == POSIXLY_BASIC and pending_text:
1383 # bad_prog (INCOMPLETE_CMD)
1384
1385 # no return, vector is edited in place
1386
1387
1388 # normalize_text() - Translation not needed
1389
1390
1391 # `str' is a string (from the command line) that contains a sed command.
1392 # Compile the command, and add it to the end of `cur_program'.
1393 def compile_string(cur_program, string):
1394 # string_expr_count = 0
1395
1396 # prog and cur_input are global classes
1397 prog.file = NULL
1398 prog.base = 0 # first char of the string (will be 1-based)
1399 prog.cur = prog.base
1400 prog.end = prog.cur + len(string)
1401 prog.text = string # sedparse extension
1402
1403 cur_input.line = 1 # sedparse: original was zero
1404 cur_input.name = NULL
1405 # string_expr_count += 1
1406 cur_input.string_expr_count += 1
1407
1408 compile_program(cur_program)
1409
1410 prog.base = NULL
1411 prog.cur = NULL
1412 prog.end = NULL
1413 prog.text = NULL
1414
1415 # no return, cur_program is edited in place
1416
1417
1418 # `cmdfile' is the name of a file containing sed commands.
1419 # Read them in and add them to the end of `cur_program'.
1420 def compile_file(cur_program, cmdfile):
1421 # prog and cur_input are global classes
1422
1423 if cmdfile == "-":
1424 # sedparse extension
1425 # My version of savchar() does not work when reading from STDIN. To
1426 # workaround that, read STDIN now into a temporary file and only handle
1427 # that file from now on.
1428 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
1429 file.write(sys.stdin.read())
1430 temp_filename = file.name
1431 prog.file = open(temp_filename, "r")
1432 else:
1433 prog.file = open(cmdfile, "r")
1434
1435 cur_input.line = 1
1436 cur_input.name = cmdfile
1437 cur_input.string_expr_count = 0
1438
1439 compile_program(cur_program)
1440
1441 prog.file.close()
1442 prog.file = NULL
1443
1444 # sedparse extension
1445 if cmdfile == "-":
1446 os.remove(temp_filename)
1447
1448 # no return, cur_program is edited in place
1449
1450
1451 # cleanup_program_filenames() - Translation not needed
1452
1453
1454 # Make any checks which require the whole program to have been read.
1455 # In particular: this backpatches the jump targets. (sedparse: we don't)
1456 # Any cleanup which can be done after these checks is done here also.
1457 def check_final_program(): # program):
1458 global old_text_buf
1459 global pending_text
1460
1461 # do all "{"s have a corresponding "}"?
1462 if blocks:
1463 bad_prog(EXCESS_OPEN_BRACE)
1464
1465 # was the final command an unterminated a/c/i command?
1466 if pending_text:
1467 debug("pending_text: %r" % pending_text)
1468 old_text_buf.text = pending_text[:]
1469 free_buffer(pending_text)
1470 pending_text = NULL
1471
1472
1473 # rewind_read_files() - Translation not needed
1474 # finish_program() - Translation not needed
1475
1476
1477 ######################################## end of translations
1478
1479 # From now on it's all sedparse exclusive code
1480
1481 PARSER_DEBUG = False
1482
1483
1484 def debug(msg, stats=False):
1485 if PARSER_DEBUG:
1486 if stats:
1487 print(
1488 "exp=%s line=%s cur=%s end=%s text=%r ch=%r"
1489 % (
1490 cur_input.string_expr_count,
1491 cur_input.line,
1492 prog.cur,
1493 prog.end,
1494 prog.text,
1495 msg,
1496 ),
1497 file=sys.stderr,
1498 )
1499 else:
1500 print(msg, file=sys.stderr)
1501
1502
1503 def reset_globals():
1504 """
1505 In the original C code, any error aborts the program. Here, we throw an
1506 exception. This can be caught and at that point, the module globals are
1507 still holding data from the previous parsing. We need to clean up everything
1508 so the next call to `compile_*()` will act on fresh, uncontaminated data.
1509 """
1510 global blocks
1511 global old_text_buf
1512 global pending_text
1513
1514 blocks = 0
1515 old_text_buf = NULL
1516 pending_text = NULL
1517
1518 # Reset compile_string()-related data
1519 prog.base = NULL
1520 prog.cur = NULL
1521 prog.end = NULL
1522 prog.text = NULL
1523
1524 # Reset compile_file()-related data
1525 if prog.file:
1526 prog.file.close()
1527 prog.file = NULL
1528
1529
1530 def to_json(obj, remove_empty=True):
1531 return json.dumps(obj, default=lambda x: x.to_dict(remove_empty), **JSON_OPTS)
1532
1533
1534 def print_program(compiled_program): # pylint: disable=unused-variable
1535 indent_level = 0
1536 indent_prefix = " " * 4
1537 for x in compiled_program:
1538 if x.cmd == "}":
1539 indent_level -= 1
1540
1541 if x.cmd == "\n":
1542 print()
1543 else:
1544 print("%s%s" % ((indent_prefix * indent_level), x))
1545
1546 if x.cmd == "{":
1547 indent_level += 1
1548
1549
1550 def get_argparser():
1551 argparser = argparse.ArgumentParser(
1552 description="Parse a sed script and show its JSON representation in STDOUT."
1553 )
1554 # For -e and -f we use the same name, metavar and help as in GNU sed
1555 argparser.add_argument(
1556 "-e",
1557 "--expression",
1558 metavar="script",
1559 dest="inputs",
1560 action="append",
1561 type=lambda x: ("e", x), # becomes a ("e", expression) tuple
1562 help="add the script to the commands to be parsed",
1563 )
1564 argparser.add_argument(
1565 "-f",
1566 "--file",
1567 metavar="script-file",
1568 dest="inputs",
1569 action="append",
1570 type=lambda x: ("f", x), # becomes a ("f", filename) tuple
1571 help="add the contents of script-file to the commands to be parsed",
1572 )
1573 argparser.add_argument(
1574 "--full", action="store_true", help="show full JSON (has empty values)"
1575 )
1576 argparser.add_argument(
1577 "-v", "--verbose", action="store_true", help="turn on verbose mode"
1578 )
1579 argparser.add_argument(
1580 "-V", "--version", action="version", version="%(prog)s " + __version__
1581 )
1582 return argparser
1583
1584
1585 def main(arguments=None):
1586 global PARSER_DEBUG
1587
1588 args = get_argparser().parse_args(arguments)
1589
1590 PARSER_DEBUG = args.verbose
1591
1592 if not args.inputs:
1593 raise RuntimeError("No sed script to be parsed. Use -e and/or -f.")
1594
1595 # Read and parse the sed script informed in -e and/or -f, respecting the
1596 # original argument order
1597 the_program = []
1598 for input_type, input_val in args.inputs:
1599 if input_type == "e":
1600 debug("\n===== Will parse expression: %s" % input_val)
1601 compile_string(the_program, input_val)
1602 elif input_type == "f":
1603 debug("\n===== Will parse file: %s" % input_val)
1604 compile_file(the_program, input_val)
1605 else:
1606 raise RuntimeError("Unknown input type '%s'" % input_type)
1607 check_final_program()
1608
1609 return to_json(the_program, not args.full)
1610
1611
1612 def entrypoint():
1613 try:
1614 print(main())
1615 sys.exit(EXIT_SUCCESS)
1616 except ParseError as err:
1617 print(err.message, file=sys.stderr)
1618 sys.exit(err.exitcode)
1619 except RuntimeError as err:
1620 sys.exit("%s: %s" % (program_name, err))
1621
1622
1623 if __name__ == "__main__":
1624 entrypoint()