Debian Codegraph @

gcc/cobol/lexio.cc

raw
1 /*
2 * Copyright (c) 2021-2025 Symas Corporation
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of the Symas Corporation nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "config.h"
32 #include <ext/stdio_filebuf.h>
33 #include "cobol-system.h"
34 #include "cbldiag.h"
35 #include "util.h"
36 #include "copybook.h"
37 #include "lexio.h"
38
39 extern int yy_flex_debug;
40
41 source_format_t& cdf_source_format();
42
43 void
44 source_format_t::infer( const char *bol, bool want_reference_format ) {
45 if( bol ) {
46 left = 7;
47 if( want_reference_format ) {
48 right = 73;
49 }
50 }
51 dbgmsg("%s:%d: %s format detected", __func__, __LINE__,
52 description());
53 }
54
55
56 // public source format test functions
57 bool is_fixed_format() { return cdf_source_format().is_fixed(); }
58 bool is_reference_format() { return cdf_source_format().is_reffmt(); }
59
60 static bool debug_mode = false;
61
62 /*
63 * The "debug mode" is a little odd, because we have to make sure a
64 * leading "D" doesn't start the verb DISPLAY (for example). If
65 * debug_mode is on, debug lines are included in the parse. If
66 * debug_mode is off but we're not in fixed_format, lines starting
67 * with "D" are also included.
68 *
69 * So, the line is excluded if: fixed format and not debug mode
70 * Else, it's included.
71 */
72
73 static inline int left_margin() {
74 return cdf_source_format().left_margin();
75 }
76 static inline int right_margin() {
77 return cdf_source_format().right_margin();
78 }
79
80 /*
81 * When setting the indicator column explicity:
82 * To get strict fixed 72-column lines, use a negative column number.
83 * When setting back to 0 (free), the right margin is also reset to 0.
84 */
85 void
86 cobol_set_indicator_column( int column );
87
88 bool include_debug() { return is_fixed_format() && debug_mode; }
89 bool set_debug( bool tf ) { return debug_mode = tf && is_fixed_format(); }
90
91 static bool nonblank( const char ch ) { return !isblank(ch); }
92
93 static inline char *
94 start_of_line( char *bol, char *eol ) {
95 bol = std::find_if(bol, eol, nonblank);
96 gcc_assert(bol < eol); // must exist
97 return bol;
98 }
99
100 static inline char *
101 continues_at( char *bol, char *eol ) {
102 if( cdf_source_format().is_free() ) return NULL; // cannot continue in free format
103 bol += left_margin();
104 if( *bol != '-' ) return NULL; // not a continuation line
105 return start_of_line(++bol, eol);
106 }
107
108 // Return pointer to indicator column. Test ch if provided.
109 // NULL means no indicator column or tested value not present.
110 static inline char *
111 indicated( char *bol, const char *eol, char ch = '\0' ) {
112 if( cdf_source_format().left_margin() == 0 && *bol != '*' ) {
113 return NULL; // no indicator column in free format, except for comments
114 }
115 gcc_assert(bol != NULL);
116 auto ind = bol + left_margin();
117 if( eol <= ind ) return NULL; // left margin would be after end of line
118 // If TAB is in the line-number region, nothing is in the indicator column.
119 bool has_tab = std::any_of(bol, ind,
120 [](const char ch) { return ch == '\t'; } );
121 if( has_tab ) return NULL;
122 if( (bol += left_margin()) > eol ) return NULL;
123 return ch == '\0' || ch == *bol? bol : NULL;
124 }
125
126 static char *
127 remove_inline_comment( char *bol, char *eol ) {
128 char *nl = std::find(bol, eol, '\n');
129
130 if( bol < nl ) {
131 static char ends = '\0';
132 std::swap(*nl, ends);
133 char *comment = strstr(bol, "*>");
134 if( comment ) {
135 std::fill(comment, nl, SPACE);
136 }
137 std::swap(*nl, ends);
138 }
139 return eol;
140 }
141
142 static void
143 erase_line( char *src, char *esrc ) {
144 dbgmsg( "%s: erasing %.*s from input", __func__, int(esrc-src), src);
145 erase_source(src, esrc);
146 }
147
148 static size_t
149 count_newlines( const char *beg, const char *end ) {
150 return std::count(beg, end, '\n');
151 }
152
153 size_t
154 filespan_t::tab_check( const char *src, const char *esrc ) {
155 static const char tab = '\t';
156
157 const char *data = src + left_margin();
158 if( data < esrc ) { // not a blank line
159 const char *tab_at = std::find(src, data, tab);
160 if( tab_at < data ) {
161 return (tab_at - src) + 1;
162 }
163 }
164 return 0;
165 }
166
167 static const auto extended_icase = regex::extended | regex::icase;
168
169 std::stack< std::list<replace_t> > replace_directives;
170
171 static bool
172 is_word_or_quote( char ch ) {
173 return ch == '"' || ch == '\'' || ISALNUM(ch);
174 }
175 /*
176 * If the replacement is not leading/trailing, the edges of the
177 * matched pattern must delimit a Cobol word. If not, add a space to
178 * the replacement.
179 */
180 static void
181 maybe_add_space(const span_t& pattern, replace_t& recognized) {
182 static const char blank[] = " ";
183 const char *befter[2] = { "", "" };
184 gcc_assert(0 < recognized.before.size());
185
186 // start of pattern and end of preceding text
187 if( pattern.p[0] == '.' && is_word_or_quote(recognized.before.p[-1]) ) {
188 befter[0] = blank;
189 }
190 // end of pattern, and start of succeeding text
191 if( pattern.pend[-1] == '.' && is_word_or_quote(recognized.before.pend[0]) ) {
192 befter[1] = blank;
193 }
194
195 if( befter[0] == blank || befter[1] == blank ) {
196 const char *s = xasprintf( "%s%.*s%s",
197 befter[0],
198 recognized.after.size(), recognized.after.p,
199 befter[1] );
200 recognized.after = span_t(s, s + strlen(s));
201 }
202 }
203
204 /*
205 * Keep track of the next pending replacement for each active REPLACE
206 * directive. For the current line, apply patterns that begins on the
207 * line. (It may match input extending beyond the current eol.)
208 *
209 * As each replacement is identified, append it to the passsed list of
210 * pending replacements. For these elements:
211 *
212 * before is a span in mfile
213 * after is dynamically allocated
214 */
215 static void
216 recognize_replacements( filespan_t mfile, std::list<replace_t>& pending_replacements ) {
217 static const char *top_of_stack_cache, *applies_to;
218
219 struct future_replacement_t {
220 replace_t directive;
221 span_t found;
222 future_replacement_t( const replace_t& replace, span_t found )
223 : directive(replace), found(found)
224 {}
225 bool operator<( const future_replacement_t& that ) const {
226 return found.p < that.found.p;
227 }
228 };
229
230 static std::list<future_replacement_t> futures;
231
232 if( replace_directives.empty() ) return;
233
234 if( ! (top_of_stack_cache == replace_directives.top().front().before.p
235 &&
236 applies_to == mfile.data) )
237 {
238 futures.clear();
239 top_of_stack_cache = replace_directives.top().front().before.p;
240 applies_to = mfile.data;
241 }
242
243 if( futures.empty() ) {
244 /*
245 * From the current point in the file, find the next match for each
246 * pattern at the top of the replacement stack.
247 */
248 for( const auto& directive : replace_directives.top() ) {
249 regex re(directive.before.p, extended_icase);
250 cmatch cm;
251
252 span_t found(mfile.eodata, mfile.eodata);
253
254 if( regex_search( mfile.ccur(),
255 const_cast<const char *>(mfile.eodata),
256 cm, re) ) {
257 gcc_assert(cm[1].matched);
258 found = span_t( cm[1].first, cm[1].second );
259 if( yy_flex_debug ) {
260 size_t n = count_newlines(mfile.data, found.p);
261 dbgmsg("%s:%d first '%.*s' is on line " HOST_SIZE_T_PRINT_UNSIGNED
262 " (offset " HOST_SIZE_T_PRINT_UNSIGNED ")", __func__, __LINE__,
263 directive.before.size(), directive.before.p,
264 (fmt_size_t)++n, (fmt_size_t)(found.p - mfile.data));
265 }
266 } else {
267 dbgmsg("%s:%d not found: '%s' in \n'%.*s'", __func__, __LINE__,
268 directive.before.p, int(strlen(directive.before.p)), mfile.cur);
269 }
270 futures.push_back( future_replacement_t(directive, found) );
271 }
272 }
273
274 gcc_assert(!futures.empty());
275 gcc_assert(futures.size() == replace_directives.top().size());
276
277 replace_t recognized;
278
279 auto pnext = std::min_element(futures.begin(), futures.end());
280
281 for( const char *bol = mfile.cur; // more than one replacement may apply to a line
282 bol <= pnext->found.p && pnext->found.p < mfile.eol; ) {
283 auto& next(*pnext);
284 recognized = replace_t( next.found, span_t(strlen(next.directive.after.p),
285 next.directive.after.p) );
286 maybe_add_space(next.directive.before, recognized);
287 pending_replacements.push_back(recognized);
288 bol = next.found.pend;
289
290 if( yy_flex_debug ) {
291 size_t n = std::count(const_cast<const char *>(mfile.data),
292 recognized.before.p, '\n');
293 dbgmsg( "%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED
294 " @ " HOST_SIZE_T_PRINT_UNSIGNED ": '%s'\n/%.*s/%.*s/",
295 __func__, __LINE__,
296 (fmt_size_t)++n, (fmt_size_t)(next.found.p - mfile.data),
297 next.directive.before.p,
298 int(recognized.before.size()), recognized.before.p,
299 int(recognized.after.size()), recognized.after.p );
300 }
301
302 // Update the futures element for this pattern
303 cmatch cm;
304
305 next.found = span_t(mfile.eodata, mfile.eodata);
306
307 regex re(next.directive.before.p, extended_icase);
308 if( regex_search(bol, const_cast<const char *>(mfile.eodata), cm, re) ) {
309 gcc_assert(cm[1].matched);
310 next.found = span_t( cm[1].first, cm[1].second );
311 size_t n = std::count(const_cast<const char *>(mfile.data),
312 next.found.p, '\n');
313 if( false )
314 dbgmsg("%s:%d next '%.*s' will be on line " HOST_SIZE_T_PRINT_UNSIGNED
315 " (offset " HOST_SIZE_T_PRINT_UNSIGNED ")", __func__, __LINE__,
316 next.directive.before.size(), next.directive.before.p,
317 (fmt_size_t)++n, (fmt_size_t)(next.found.p - mfile.data));
318 }
319 pnext = std::min_element(futures.begin(), futures.end());
320 }
321 }
322
323 static void
324 check_push_pop_directive( filespan_t& mfile ) {
325 char eol = '\0';
326 const char *p = std::find(mfile.cur, mfile.eol, '>');
327 if( ! (p < mfile.eol && p[1] == *p ) ) return;
328
329 const char pattern[] =
330 ">>[[:blank:]]*(push|pop)[[:blank:]]+"
331 "("
332 "all|"
333 "call-convention|"
334 "cobol-words|"
335 "define|"
336 "source[[:blank:]]+format|"
337 "turn"
338 ")";
339 static regex re(pattern, extended_icase);
340
341 // show contents of marked subexpressions within each match
342 cmatch cm;
343
344 std::swap(*mfile.eol, eol); // see implementation for excuses
345 bool ok = regex_search(p, const_cast<const char *>(mfile.eol), cm, re);
346 std::swap(*mfile.eol, eol);
347
348 if( ok ) {
349 gcc_assert(cm.size() > 1);
350 bool push = TOUPPER(cm[1].first[1]) == 'U';
351 switch( TOUPPER(cm[2].first[0]) ) {
352 case 'A': // ALL
353 push? cdf_push() : cdf_pop();
354 break;
355 case 'C':
356 switch( TOUPPER(cm[2].first[1]) ) {
357 case 'A': // CALL-CONVENTION
358 push? cdf_push_call_convention() : cdf_pop_call_convention();
359 break;
360 case 'O': // COBOL-WORDS
361 push? cdf_push_current_tokens() : cdf_pop_current_tokens();
362 break;
363 default:
364 gcc_unreachable();
365 }
366 break;
367 case 'D': // DEFINE
368 push? cdf_push_dictionary() : cdf_pop_dictionary();
369 break;
370 case 'S': // SOURCE FORMAT
371 push? cdf_push_source_format() : cdf_pop_source_format();
372 break;
373 case 'T': // TURN
374 push? cdf_push_enabled_exceptions() : cdf_pop_enabled_exceptions();
375 break;
376 default:
377 gcc_unreachable();
378 }
379 erase_line(const_cast<char*>(cm[0].first),
380 const_cast<char*>(cm[0].second));
381 }
382 }
383
384 static void
385 check_source_format_directive( filespan_t& mfile ) {
386 char eol = '\0';
387 const char *p = std::find(mfile.cur, mfile.eol, '>');
388 if( ! (p < mfile.eol && p[1] == *p ) ) return;
389
390 const char pattern[] =
391 ">>[[:blank:]]*source[[:blank:]]+"
392 "(format[[:blank:]]+)?"
393 "(is[[:blank:]]+)?"
394 "(fixed|free)";
395 static regex re(pattern, extended_icase);
396
397 // show contents of marked subexpressions within each match
398 cmatch cm;
399
400 std::swap(*mfile.eol, eol); // see implementation for excuses
401 bool ok = regex_search(p, const_cast<const char *>(mfile.eol), cm, re);
402 std::swap(*mfile.eol, eol);
403
404 if( ok ) {
405 gcc_assert(cm.size() > 1);
406 switch( cm[3].length() ) {
407 case 4:
408 cobol_set_indicator_column(0);
409 break;
410 case 5:
411 cobol_set_indicator_column(-7);
412 break;
413 default:
414 gcc_assert(cm[3].length() == 4 || cm[3].length() == 5);
415 break;
416 }
417
418 dbgmsg( "%s:%d: %s format set, on line " HOST_SIZE_T_PRINT_UNSIGNED,
419 __func__, __LINE__,
420 cdf_source_format().description(),
421 (fmt_size_t)mfile.lineno() );
422 char *bol = cdf_source_format().is_fixed()? mfile.cur : const_cast<char*>(cm[0].first);
423 gcc_assert(cm[0].second <= mfile.eol);
424 erase_line(bol, const_cast<char*>(cm[0].second));
425 }
426 }
427
428 struct buffer_t : public bytespan_t {
429 char *pos; // current output position
430
431 buffer_t( char *data, char *eodata )
432 : bytespan_t(data, eodata)
433 , pos(data)
434 {
435 if(pos) *pos = '\0';
436 }
437
438 size_t nline() const {
439 gcc_assert(data <= pos);
440 return std::count(data, pos, '\n');
441 }
442 size_t free_space() const { gcc_assert(pos <= eodata); return eodata - pos; }
443
444 bool pad_lines( size_t goal ) {
445 while( nline() < goal ) {
446 if( pos == eodata ) return false;
447 *pos++ = '\n';
448 }
449 return true;
450 }
451
452 void show() const {
453 gcc_assert(data <= pos);
454 dbgmsg("flex input buffer: '%.*s'\n[xelf]", int(pos - data), data);
455 }
456 void dump() const {
457 #ifdef GETENV_OK
458 if( getenv("lexer_input") ) show();
459 #endif
460 }
461 };
462
463 static inline bool is_p( char ch ) { return TOUPPER(ch) == 'P'; }
464
465 static bool
466 is_program_id( const char *p, const char *eol ) {
467 static const std::string program_id("PROGRAM-ID");
468 auto eop = p + program_id.size();
469 if( eop < eol ) {
470 // PROGRAM-ID must be followed by a dot, perhaps with intervening whitespace.
471 for( const char *dot=eop; dot < eol && *dot != '.'; dot++ ) {
472 if( !ISSPACE(*dot) ) return false;
473 }
474 std::string line (p, eop);
475 std::transform(line.begin(), line.end(), line.begin(), ::toupper);
476 return line == program_id;
477 }
478 return false;
479 }
480
481 const char * esc( size_t len, const char input[] );
482
483 static bool
484 is_word_char( char ch ) {
485 switch(ch) {
486 case '$':
487 case '-':
488 case '_':
489 return true;
490 }
491 return ISALNUM(ch);
492 }
493
494 static bool
495 is_numeric_char( char ch ) {
496 return ISDIGIT(ch)
497 || TOUPPER(ch) == 'E'
498 || ch == '.'
499 || ch == ','
500 ;
501 }
502
503 static bool
504 is_numeric_term( span_t term ) {
505 gcc_assert(term.p);
506 if( term.p[0] == '+' || term.p[0] == '-' ) term.p++;
507 auto p = std::find_if( term.p, term.pend,
508 []( char ch ) {
509 return ! is_numeric_char(ch);
510 } );
511 return p == term.pend;
512 }
513
514 struct replacing_term_t {
515 bool matched, done;
516 span_t leading_trailing, term, stmt;
517
518 explicit replacing_term_t(const char input[])
519 : matched(false), done(false), stmt(span_t(input, input))
520 {}
521 };
522
523 extern YYLTYPE yylloc;
524
525 static const char *
526 last_newline (const char *p, const char *pend ) {
527 size_t len = pend - p;
528 return static_cast<const char *>( memrchr( p, '\n', len ) );
529 }
530 /*
531 * For some statement parsed with regex_search, set yyloc to indicate the line
532 * and column spans of the term. Assume stmt begins at the start of a line.
533 */
534 static void
535 update_yylloc( const csub_match& stmt, const csub_match& term ) {
536 gcc_assert(stmt.first <= term.first && term.second <= stmt.second);
537
538 class dump_loc_on_exit {
539 public:
540 dump_loc_on_exit() {
541 if( gcobol_getenv( "update_yylloc" ) )
542 location_dump( "update_yylloc", __LINE__, "begin", yylloc);
543 }
544 ~dump_loc_on_exit() {
545 if( gcobol_getenv( "update_yylloc" ) )
546 location_dump( "update_yylloc", __LINE__, "end ", yylloc);
547 }
548 } dloe;
549
550 size_t nline = std::count( stmt.first, term.second, '\n' );
551 size_t n = std::count( term.first, term.second, '\n' );
552
553 if( nline ) {
554 yylloc.last_line += nline;
555 yylloc.first_line = yylloc.last_line - n;
556 }
557
558 /*
559 * Set the column span for the term.
560 */
561 const char *p = last_newline(stmt.first, stmt.second);
562 if( !p ) { // no newlines in entire statement
563 yylloc.first_column = (term.first - stmt.first) + 1;
564 yylloc.last_column = (term.second - stmt.first) + 1;
565 return;
566 }
567
568 p = last_newline(stmt.first, term.first);
569 if( !p ) { // no newlines before term
570 yylloc.first_column = (term.first - stmt.first) + 1;
571 p = last_newline(term.first, term.second);
572 gcc_assert(p); // newline must be in term
573 yylloc.last_column = (term.second - p) + 1;
574 return;
575 }
576
577 const char *bol = p; // bol points to last newline before term
578
579 yylloc.first_column = term.first - bol;
580 p = last_newline(term.first, term.second);
581 if( p ) { // term has newlines, too
582 yylloc.last_column = (p - term.first);
583 } else {
584 yylloc.last_column = yylloc.first_column + term.length();
585 }
586 }
587
588 static replacing_term_t
589 parse_replacing_term( const char *stmt, const char *estmt ) {
590 gcc_assert(stmt); gcc_assert(estmt); gcc_assert(stmt <= estmt);
591 replacing_term_t output(stmt);
592
593 static const char pattern[] =
594 "^([[:space:];,]+(LEADING|TRAILING|BY))?" // 1, 2
595 "[[:space:];,]+" // leading space between pairs
596 "(" // 3
597 "(\"" "([\"]{2}|[^\"])*" "\")" // 4, 5
598 "|" "('" "([']{2}|[^'])*" "')" // 6, 7
599 "|" "(" "[+-]?[[:alnum:]]+([_-]+[[:alnum:]]+)*" ")" // 8, 9
600 "|" "(==(" "(=?[^=]+)*" ")==)" // 10, 11, 12
601 ")"
602 "(([[:space:];,]+[\"'=[:alnum:]+-]{1,2})" "|" "[[:space:];,]*([.]))?" // 13, 14, 15
603 ;
604
605 static regex re(pattern, extended_icase);
606 cmatch cm;
607
608 if( ! regex_search( stmt, estmt, cm, re) ) return output;
609
610 bool replacing_term = cm[2].matched && TOUPPER(cm[2].first[0]) == 'B';
611
612 if( cm[2].matched && ! replacing_term ) {
613 output.leading_trailing = cm[2];
614 }
615
616 // Apply such that quoted matches supersede word matches.
617 if( cm[11].matched ) output.term = cm[11];
618 if( cm[ 8].matched ) output.term = cm[ 8];
619 if( cm[ 6].matched ) output.term = cm[ 6];
620 if( cm[ 4].matched ) output.term = cm[ 4];
621
622 // The matched segment extends to the end of the matched term, or to
623 // the dot at end of statement. Include the pseudotext ==, if found.
624 output.stmt = span_t(cm[0].first, output.term.pend);
625 if( cm[10].matched ) output.stmt.pend = cm[10].second;
626
627 if( cm[15].matched && ISSPACE(cm[15].second[0]) ) { // matched end of statement
628 output.done = output.matched = true;
629 output.stmt = cm[0];
630 gcc_assert(output.stmt.pend[-1] == '.');
631 dbgmsg("%s:%d: done at '%.*s'", __func__, __LINE__,
632 output.term.size(), output.term.p);
633 return output;
634 }
635
636 if( is_numeric_term(output.term) ) {
637 output.matched = output.stmt.p < output.term.p;
638 gcc_assert(output.matched);
639 // look for fractional part
640 if( is_numeric_char(*output.term.pend) && ISDIGIT(output.term.pend[1]) ) {
641 gcc_assert(!ISDIGIT(*output.term.pend));
642 auto p = std::find_if(++output.term.pend, estmt,
643 []( char ch ) { return !ISDIGIT(ch); } );
644 output.stmt.pend = output.term.pend = p;
645 output.done = '.' == output.stmt.pend[0] && ISSPACE(output.stmt.pend[1]);
646 if( output.done ) output.stmt.pend++;
647 }
648 dbgmsg("%s:%d: %s '%.*s'", __func__, __LINE__,
649 output.done? "done at" : "term is",
650 output.term.size(), output.term.p);
651 return output;
652 }
653
654 if( yy_flex_debug ) { // should be looking only for words
655 dbgmsg("%s:%d: not done, working with '%.*s'", __func__, __LINE__,
656 cm[0].length(), cm[0].first);
657 int i=0;
658 for( auto m : cm ) {
659 if( m.matched )
660 dbgmsg("%4d) '%.*s'", i, m.length(), m.first);
661 i++;
662 }
663 }
664
665 if( !cm[8].matched ) {
666 output.matched = output.stmt.p < output.term.p;
667 gcc_assert(output.matched);
668 dbgmsg("%s:%d: term is '%.*s'", __func__, __LINE__,
669 output.term.size(), output.term.p);
670 return output;
671 }
672
673 bool extraneous_replacing = 'R' == TOUPPER(cm[8].first[0]); // maybe
674 if( extraneous_replacing ) { // prove it
675 static const char replacing[] = "REPLACING";
676 for( size_t i=0; i < strlen(replacing); i++ ) {
677 if( replacing[i] != TOUPPER(cm[8].first[i]) ) {
678 extraneous_replacing = false;
679 break;
680 }
681 }
682 if( extraneous_replacing ) {
683 update_yylloc( cm[0], cm[8] );
684 yywarn("syntax error: invalid '%.*s'", cm[8].length(), cm[8].first);
685 output.matched = false;
686 return output;
687 }
688 }
689
690 gcc_assert(cm[8].matched);
691 gcc_assert(0 < output.term.size());
692
693 dbgmsg("%s:%d: more words starting at '%.80s'", __func__, __LINE__,
694 output.term.pend);
695
696 static const char term_pattern[] =
697 "^[[:space:]]+"
698 "(" "(IN|OF)[[:space:]]+" ")" // 1, 2
699 "(" "[+-]?[[:alnum:]]+([$_-]+[[:alnum:]]+)*" ")" // 3, 4
700 "(" "[[:space:]]*[(]" ")?" // 5
701 "(([[:space:]]+[\"'=[:alnum:]+-]{1,2})" "|" "[[:space:]]*([.]))?" // 6, 7, 8
702 ;
703 static const char paren_pattern[] =
704 "^[[:space:]]*"
705 "(" "[()][^()]*[()]" ")" // 1
706 "(([[:space:]]+[\"'=[:alnum:]+-]{1,2})" "|" "[[:space:]]*([.]))?" // 2, 3, 4
707 ;
708
709 regex term_re(term_pattern, extended_icase);
710 regex paren_re(paren_pattern, extended_icase);
711 ssize_t nsub = 0;
712
713 while( regex_search( output.term.pend, estmt, cm, term_re) ) {
714 output.stmt.pend = output.term.pend = cm[3].second; // found a word
715 if( cm[5].matched ) break; // found left parenthesis
716 const csub_match& done(cm[8]);
717 if( done.matched ) {
718 output.done = output.matched = output.stmt.p < output.term.p;
719 gcc_assert(output.done);
720 goto matched;
721 }
722 }
723
724 // match subscripts, if any
725 while( regex_search( output.term.pend, estmt, cm, paren_re) ) {
726 output.stmt.pend = output.term.pend = cm[1].second;
727 if( cm[1].first[0] == '(' ) nsub++;
728 if( cm[1].first[0] == ')' ) nsub--;
729 if( cm[1].second[-1] == '(' ) nsub++;
730 if( cm[1].second[-1] == ')' ) nsub--;
731
732 const csub_match& done(cm[4]);
733 if( done.matched ) {
734 output.matched = output.stmt.p < output.term.p;
735 output.stmt.pend = done.second;
736 output.done = output.stmt.pend[-1] == '.';
737 goto matched;
738 }
739
740 if( nsub == 0 ) break;
741 }
742
743 matched:
744 output.matched = output.stmt.p < output.term.p;
745
746 if( yy_flex_debug ) {
747 const char *status = "unmatched";
748 if( output.matched ) status = output.done? "done" : "matched";
749 dbgmsg("%s:%d: %s term is '%.*s'", __func__, __LINE__, status,
750 output.term.size(), output.term.p? output.term.p : "");
751 }
752 return output;
753 }
754
755 struct replacing_pair_t {
756 span_t leading_trailing, stmt;
757 replace_t replace;
758
759 bool matched() const { return 0 < stmt.size(); }
760 bool done() const { return matched() && stmt.pend[-1] == '.'; }
761 };
762 static replacing_pair_t
763 parse_replacing_pair( const char *stmt, const char *estmt ) {
764 replacing_pair_t pair;
765
766 pair.replace = replace_t();
767 auto parsed = parse_replacing_term( stmt, estmt ); // before
768 if( parsed.matched ) {
769 if( parsed.term.size() == 0 ) return pair; // failure: empty before string
770 pair.leading_trailing = parsed.leading_trailing;
771 pair.stmt = parsed.stmt;
772 pair.replace.before = parsed.term;
773
774 if( !parsed.done ) {
775 parsed = parse_replacing_term( pair.stmt.pend, estmt ); // after
776 if( parsed.matched ) {
777 pair.stmt.pend = parsed.stmt.pend;
778 pair.replace.after = parsed.term;
779 } else {
780 dbgmsg("%s:%d: not matched '%.*s'", __func__, __LINE__,
781 pair.stmt.size(), pair.stmt.p);
782 }
783 }
784 if( yy_flex_debug ) {
785 const char *status = "unmatched";
786 if( pair.matched() ) status = pair.done()? "done" : "matched";
787 dbgmsg("%s:%d: [%s] replacing '%.*s' with '%.*s'", __func__, __LINE__,
788 status,
789 pair.replace.before.size(), pair.replace.before.p,
790 pair.replace.after.size(), pair.replace.after.p);
791 }
792 } else {
793 for( auto p = stmt; (p = std::find(p, estmt, '.')) < estmt; p++ ) {
794 if( ISSPACE(p[1]) ) {
795 pair.stmt = span_t(stmt, ++p);
796 break;
797 }
798 }
799 if( pair.stmt.p ) {
800 yywarn("CDF syntax error '%.*s'", (int)pair.stmt.size(), pair.stmt.p);
801 }
802 else {
803 // This eliminated a compiler warning about "format-overflow"
804 yywarn("CDF syntax error");
805 }
806 pair.stmt = span_t(size_t(0), stmt);
807 pair.replace = replace_t();
808 }
809 return pair;
810 }
811
812 static std::pair<std::list<replace_t>, char *>
813 parse_replace_pairs( const char *stmt, const char *estmt, bool is_copy_stmt ) {
814 std::list<replace_t> pairs ;
815
816 static const char any_ch[] = ".";
817 static const char word_ch[] = "[[:alnum:]$_-]";
818 static const char nonword_ch[] = "[^[:alnum:]\"'$_-]";
819
820 // Pattern to find one REPLACE pseudo-text pair
821 static const char replace_pattern[] =
822 "([[:space:]]+(LEADING|TRAILING))?" // 1, 2
823 "[[:space:]]+"
824 "==(" "(=?[^=]+)+" ")==" // 3, 4
825 "[[:space:]]+BY[[:space:]]+"
826 "==(" "(=?[^=]+)*" ")==" // 5, 6
827 "(([[:space:]]+[\"'=[:alnum:]+-]{1,2})" "|" "[[:space:]]*([.]))?" // 7, 8, 9
828 ;
829
830 regex pair_re(replace_pattern, extended_icase);
831 cmatch cm;
832 replacing_pair_t parsed;
833 bool end_of_stmt = false;
834
835 for( auto p = stmt; p < estmt && !end_of_stmt; p = parsed.stmt.pend ) {
836 if( is_copy_stmt ) {
837 parsed = parse_replacing_pair(p, estmt);
838 if( parsed.replace.before.size() == 0 ) break; // empty before
839 if( parsed.replace.after.p == NULL ) break; // invalid after
840 end_of_stmt = parsed.done();
841 } else {
842 if( ! regex_search( p, estmt, cm, pair_re) ) break;
843 // Report findings.
844 if( false && yy_flex_debug ) {
845 for( size_t i=0; i < cm.size(); i++ ) {
846 dbgmsg("%s: %s " HOST_SIZE_T_PRINT_UNSIGNED ": '%.*s'", __func__,
847 cm[i].matched? "Pair" : "pair",
848 (fmt_size_t)i,
849 cm[i].matched? int(cm[i].length()) : 0,
850 cm[i].matched? cm[i].first : "");
851 }
852 }
853 gcc_assert(cm[3].matched);
854 gcc_assert(cm[5].matched);
855 parsed.leading_trailing = cm[2];
856 parsed.replace.before = cm[3];
857 parsed.replace.after = cm[5];
858
859 parsed.stmt = cm[0];
860 // If not done, exclude trailing portion from statement match.
861 if( !parsed.done() && cm[8].matched ) {
862 gcc_assert(!cm[9].matched);
863 parsed.stmt.pend = cm[8].first;
864 }
865 }
866
867 span_t& before(parsed.replace.before);
868 const span_t& after(parsed.replace.after);
869
870 const char *befter[2] = { nonword_ch, nonword_ch };
871 gcc_assert(before.p < before.pend);
872 if( !is_word_char(before.p[0]) ) befter[0] = any_ch;
873 if( !is_word_char(before.pend[-1]) ) befter[1] = any_ch;
874
875 const char *src = esc(before.size(), before.p);
876
877 if( parsed.leading_trailing.size() > 0 ) {
878 switch( TOUPPER(parsed.leading_trailing.p[0]) ) {
879 case 'L': // leading
880 befter[1] = word_ch;
881 break;
882 case 'T': // trailing
883 befter[0] = word_ch;
884 break;
885 default:
886 gcc_unreachable();
887 }
888 dbgmsg("%s:%d: dealing with %.*s", __func__, __LINE__,
889 int(parsed.leading_trailing.size()), parsed.leading_trailing.p);
890 }
891
892 src = xasprintf("%s(%s)%s", befter[0], src, befter[1]);
893
894 struct { span_t before, after; } output;
895 output.before = span_t(strlen(src), src);
896 output.after = after.dup();
897
898 gcc_assert(!before.has_nul());
899 pairs.push_back( replace_t( output.before, output.after ) );
900
901 // COPY REPLACING matches end-of-statment here
902 // REPLACE matched end-of-statement in caller, and estmt[-1] == '.'
903 if( is_copy_stmt && parsed.stmt.pend[-1] == '.' ) break;
904 }
905
906 if( yy_flex_debug ) {
907 dbgmsg( "%s:%d: %s: " HOST_SIZE_T_PRINT_UNSIGNED " pairs parsed from '%.*s'",
908 __func__, __LINE__,
909 parsed.done() ? "done" : "not done",
910 (fmt_size_t)pairs.size(), parsed.stmt.size(), parsed.stmt.p );
911 int i = 0;
912 for( const auto& replace : pairs ) {
913 dbgmsg("%s:%d:%4d: '%s' => '%s'", __func__, __LINE__,
914 ++i, replace.before.p, replace.after.p);
915 }
916 }
917 if( !parsed.done() ) {
918 pairs.clear();
919 return std::make_pair(pairs, const_cast<char*>(stmt));
920 }
921
922 return std::make_pair(pairs, const_cast<char*>(parsed.stmt.pend));
923 }
924
925 struct copy_descr_t {
926 bool parsed;
927 int fd;
928 size_t nreplace;
929 span_t partial_line, erased_lines;
930
931 copy_descr_t( const char *line, const char *eol)
932 : parsed(false), fd(-1), nreplace(0), partial_line(line, eol) {}
933 };
934
935 static YYLTYPE
936 location_in( const filespan_t& mfile, const csub_match& cm ) {
937 YYLTYPE loc {
938 int(mfile.lineno() + 1), int(mfile.colno() + 1),
939 int(mfile.lineno() + 1), int(mfile.colno() + 1)
940 };
941 gcc_assert(mfile.cur <= cm.first && cm.second <= mfile.eodata);
942 auto nline = std::count(cm.first, cm.second, '\n');
943 if( nline ) {
944 gcc_assert(nline < loc.first_line);
945 loc.first_line -= nline;
946 auto p = static_cast<const char*>(memrchr(cm.first, '\n', cm.length()));
947 loc.last_column = (cm.second) - p;
948 }
949 location_dump(__func__, __LINE__, "copy?", loc);
950 return loc;
951 }
952
953 static copy_descr_t
954 parse_copy_directive( filespan_t& mfile ) {
955 static const char *most_recent_buffer;
956 static span_t copy_stmt(mfile.eodata, mfile.eodata);
957
958 static const char pattern[] =
959 "COPY" "[[:space:]]+"
960 /* 1 */ "("
961 /*2,3*/ "\"(" "([\"]{2}|[^\"])+" ")\""
962 /*4,5*/ "|" "'(" "([']{2}|[^'])+" ")[']"
963 /*6,7*/ "|" "(" "[[:alnum:]]+([_-]+[[:alnum:]]+)*" ")"
964 /* */ ")"
965 /* 8 */ "("
966 /* 9 */ "[[:space:]]+(OF|IN)[[:space:]]+"
967 /* 10*/ "("
968 /*11,12*/ "(\"" "([\"]{2}|[^\"])+" "\")"
969 /*13,14*/ "|" "('" "([']{2}|[^'])+" "')"
970 /*15,16*/ "|" "(" "[[:alnum:]]+([_-]+[[:alnum:]]+)*" ")"
971 /* */ ")"
972 /* */ ")?"
973 /*17,18*/ "([[:space:]]+SUPPRESS([[:space:]]+PRINTING)?)?"
974 /*19,20 */ "(" "([[:space:]]*[.])" "|" "[[:space:]]+REPLACING" ")"
975 ;
976
977 static regex re(pattern, extended_icase);
978 cmatch cm;
979 copy_descr_t outcome(mfile.cur, mfile.cur);
980
981 // COPY appears in current buffer?
982 if( most_recent_buffer != mfile.data || copy_stmt.p < mfile.cur ) {
983 most_recent_buffer = mfile.data;
984 copy_stmt.p = mfile.eodata;
985
986 if( regex_search(mfile.ccur(),
987 const_cast<const char *>(mfile.eodata), cm, re) ) {
988 copy_stmt = span_t( cm[0].first, cm[0].second );
989 if( yy_flex_debug ) {
990 size_t nnl = 1 + count_newlines(mfile.data, copy_stmt.p);
991 size_t nst = 1 + count_newlines(copy_stmt.p, copy_stmt.pend);
992 dbgmsg("%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED
993 ": COPY directive is " HOST_SIZE_T_PRINT_UNSIGNED " lines '%.*s'",
994 __func__, __LINE__,
995 (fmt_size_t)nnl, (fmt_size_t)nst, copy_stmt.size(), copy_stmt.p);
996 }
997 }
998 }
999
1000 // If COPY appears on the current line, parse it completely this time.
1001 if( mfile.cur <= copy_stmt.p &&
1002 copy_stmt.p < mfile.eol ) {
1003 outcome.parsed = regex_search(copy_stmt.p, copy_stmt.pend, cm, re);
1004 gcc_assert(outcome.parsed);
1005 outcome.partial_line = span_t(mfile.cur, copy_stmt.p);
1006
1007 if( yy_flex_debug ) {
1008 dbgmsg(HOST_SIZE_T_PRINT_UNSIGNED " expressions",
1009 (fmt_size_t)std::count(pattern, pattern + sizeof(pattern), '('));
1010 int i = 0;
1011 for( const auto& m : cm ) {
1012 if( m.matched )
1013 dbgmsg("%s:%d: %2d: '%.*s'", __func__, __LINE__,
1014 i, int(m.length()), m.first);
1015 i++;
1016 }
1017 }
1018
1019 auto& copybook_name = cm[1];
1020 auto& library_name = cm[10];
1021
1022 bool replacing = !cm[20].matched;
1023
1024 if( library_name.matched ) {
1025 YYLTYPE loc = location_in( mfile, library_name );
1026 copybook.library( loc, xstrndup(library_name.first, library_name.length()) );
1027 }
1028 YYLTYPE loc = location_in( mfile, copybook_name );
1029 outcome.fd = copybook.open( loc, xstrndup(copybook_name.first,
1030 copybook_name.length()) );
1031 if( outcome.fd == -1 ) { // let parser report missing copybook
1032 dbgmsg("%s:%d: (no copybook '%s' found)", __func__, __LINE__, copybook.source());
1033 return outcome;
1034 }
1035
1036 if( replacing ) {
1037 std::pair<std::list<replace_t>, char*>
1038 result = parse_replace_pairs( cm[0].second, mfile.eodata, true );
1039
1040 const std::list<replace_t>& replacements(result.first);
1041 outcome.parsed = (outcome.nreplace = replacements.size()) > 0;
1042 if( outcome.parsed ) {
1043 replace_directives.push(replacements);
1044 }
1045 copy_stmt.pend = result.second;
1046
1047 // Maybe we don't need these. We'll see.
1048 for( const auto& r : replacements ) {
1049 copybook.replacement(pseudo_e, r.before.dup().p, r.after.dup().p);
1050 }
1051 }
1052
1053 // If the parse failed, pass it through to the parser for analysis.
1054 if( outcome.parsed ) {
1055 erase_line( const_cast<char*>(copy_stmt.p),
1056 const_cast<char*>(copy_stmt.pend));
1057 outcome.erased_lines = copy_stmt;
1058 }
1059
1060 mfile.eol = const_cast<char*>(copy_stmt.pend);
1061 mfile.next_line();
1062 }
1063 return outcome;
1064 }
1065
1066 static char *
1067 parse_replace_last_off( const filespan_t& mfile ) {
1068 static const char pattern[] =
1069 "REPLACE" "[[:space:]]+"
1070 "(LAST[[:space:]]+)?OFF[[:space:]]*[.]"
1071 ;
1072 static regex re(pattern, extended_icase);
1073 cmatch cm;
1074
1075 // REPLACE [LAST] OFF?
1076 bool found = regex_search(mfile.ccur(),
1077 const_cast<const char *>(mfile.eodata), cm, re);
1078 gcc_assert(found); // caller ensures
1079
1080 gcc_assert(cm.size() == 2);
1081 // LAST OFF removes most recent REPLACE
1082 if( cm[1].matched ) {
1083 gcc_assert(TOUPPER(cm[1].first[0]) == 'L');
1084 if( ! replace_directives.empty() ) {
1085 replace_directives.pop();
1086 }
1087 } else { // OFF clears the REPLACE stack
1088 while( ! replace_directives.empty() ) {
1089 replace_directives.pop();
1090 }
1091 }
1092
1093 dbgmsg( "%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED ": parsed '%.*s', ",
1094 __func__, __LINE__,
1095 (fmt_size_t)mfile.lineno(), int(cm[0].length()), cm[0].first );
1096
1097 // Remove statement from input
1098 erase_line(const_cast<char*>(cm[0].first),
1099 const_cast<char*>(cm[0].second));
1100
1101 return const_cast<char*>(cm[0].second);
1102 }
1103
1104 static span_t
1105 parse_replace_text( filespan_t& mfile ) {
1106 static const char pattern[] =
1107 /* 0 */ "REPLACE"
1108 /* 1 */ "([[:space:]]+ALSO)?"
1109 /* 2 */ "("
1110 /*3,4*/ "([[:space:]]+(LEADING|TRAILING))?"
1111 /* 5 */ "([[:space:]]+"
1112 /* 6 */ "==" "(=?[^=]+)+" "=="
1113 /* */ "[[:space:]]+BY[[:space:]]+"
1114 /* 7 */ "==" "(=?[^=]+)*" "=="
1115 /* */ ")"
1116 /* */ ")+[[:space:]]*[.]"
1117 ;
1118 static regex re(pattern, extended_icase);
1119 cmatch cm;
1120 const size_t current_lineno(mfile.lineno());
1121
1122 if( false && yy_flex_debug ) {
1123 auto pend = mfile.eol;
1124 gcc_assert(mfile.line_length() > 2);
1125 if( pend[-1] == '\n' ) pend -= 2;
1126 auto len = int(pend - mfile.cur);
1127 dbgmsg("%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED ": parsing '%.*s",
1128 __func__, __LINE__,
1129 (fmt_size_t)current_lineno, len, mfile.cur);
1130 }
1131
1132 if( ! regex_search(mfile.ccur(), mfile.eodata, cm, re) ) {
1133 dbgmsg( "%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED
1134 ": not a REPLACE statement:\n'%.*s'",
1135 __func__, __LINE__, (fmt_size_t)current_lineno,
1136 int(mfile.line_length()), mfile.cur );
1137 return span_t();
1138 }
1139
1140 // Report findings.
1141 if( yy_flex_debug ) {
1142 dbgmsg(HOST_SIZE_T_PRINT_UNSIGNED " expressions",
1143 (fmt_size_t)std::count(pattern, pattern + sizeof(pattern), '('));
1144 int i = 0;
1145 for( const auto& m : cm ) {
1146 if( m.matched )
1147 dbgmsg("%s:%d: %2d: '%.*s'", __func__, __LINE__,
1148 i, int(m.length()), m.first);
1149 i++;
1150 }
1151 }
1152
1153 gcc_assert(cm.size() > 7);
1154
1155 // Update active REPLACE stack
1156 if( ! cm[1].matched ) { // ALSO pushes, else clear stack and push one.
1157 while( !replace_directives.empty() ) {
1158 replace_directives.pop();
1159 }
1160 } else {
1161 gcc_assert(TOUPPER(cm[1].first[0]) == 'A');
1162 }
1163
1164 span_t replace_stmt(cm[0].first, cm[0].second);
1165
1166 std::pair<std::list<replace_t>, char*>
1167 result = parse_replace_pairs(replace_stmt.p, replace_stmt.pend, false);
1168 const std::list<replace_t>& replacements(result.first);
1169 replace_directives.push( replacements );
1170
1171 if( yy_flex_debug ) {
1172 dbgmsg( "%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED ": " HOST_SIZE_T_PRINT_UNSIGNED
1173 " pairs parsed from '%.*s'", __func__, __LINE__,
1174 (fmt_size_t)current_lineno, (fmt_size_t)replacements.size(),
1175 int(replace_stmt.size()), replace_stmt.p );
1176 for( const auto& replace : replacements ) {
1177 int i = 0;
1178 dbgmsg("%s:%d:%4d: '%s' => '%s'", __func__, __LINE__,
1179 ++i, replace.before.p, replace.after.p);
1180 }
1181 }
1182
1183 // Remove statement from input
1184 erase_line(const_cast<char*>(replace_stmt.p),
1185 const_cast<char*>(replace_stmt.pend));
1186
1187 return replace_stmt;
1188 }
1189
1190 static span_t
1191 parse_replace_directive( filespan_t& mfile ) {
1192 static const char *most_recent_buffer, *next_directive;
1193 static bool off_coming_up;
1194 static const char pattern[] =
1195 "REPLACE" "[[:space:]]+" "(LAST|OFF|ALSO|LEADING|TRAILING|==)";
1196
1197 static regex re(pattern, extended_icase);
1198 cmatch cm;
1199
1200 // REPLACE appears in current buffer?
1201 if( most_recent_buffer != mfile.data || next_directive < mfile.cur ) {
1202 most_recent_buffer = mfile.data;
1203 next_directive = mfile.eodata;
1204
1205 if( regex_search(mfile.ccur(),
1206 const_cast<const char *>(mfile.eodata), cm, re) ) {
1207 gcc_assert(cm[1].matched);
1208 next_directive = cm[0].first;
1209
1210 switch( TOUPPER(cm[1].first[0]) ) {
1211 case 'L':
1212 off_coming_up = 'A' == TOUPPER(cm[1].first[1]); // LAST OFF, else LEADING
1213 break;
1214 case 'O': // OFF
1215 off_coming_up = true;
1216 break;
1217 case 'A': case 'T': case '=': // [ALSO] [ eading/Trailing] == ...
1218 off_coming_up = false;
1219 break;
1220 default:
1221 gcc_unreachable();
1222 }
1223 }
1224 }
1225
1226 span_t erased;
1227 // REPLACE appears on current line?
1228 if( mfile.cur <= next_directive &&
1229 next_directive < mfile.eol ) {
1230 if( off_coming_up ) {
1231 parse_replace_last_off(mfile);
1232 } else {
1233 erased = parse_replace_text(mfile);
1234 }
1235 }
1236 return erased;
1237 }
1238
1239 /*
1240 * Maintain the number of newlines by counting those that will be
1241 * overwritten, and appending them to the appended line. Return the
1242 * new EOL pointer.
1243 *
1244 * The newlines accumulate past eodata, at the start of the blank
1245 * lines created by the caller.
1246 */
1247 char *
1248 bytespan_t::append( const char *input, const char *eoinput ) {
1249 gcc_assert(data < eodata);
1250
1251 #define LEXIO 0
1252 #if LEXIO
1253 auto nq = std::count_if(data, eodata, isquote);
1254 dbgmsg("%s:%3d: input ------ '%.*s'", __func__, __LINE__, int(eoinput - input), input);
1255 dbgmsg("%s:%3d: precondition '%.*s' (" HOST_SIZE_T_PRINT_UNSIGNED ": %s)",
1256 __func__, __LINE__,
1257 int(size()), data, (fmt_size_t)nq, in_string()? "in string" : "not in string");
1258 #endif
1259 if( !in_string() ) { // Remove trailing space unless it's part of a literal.
1260 while(data < eodata && ISSPACE(eodata[-1])) eodata--;
1261 gcc_assert(ISSPACE(eodata[0]));
1262 gcc_assert(data == eodata || !ISSPACE(eodata[-1]));
1263 }
1264 // skip leading blanks
1265 while( input < eoinput && ISSPACE(*input) ) input++;
1266 if( isquote(*input) ) input++;
1267
1268 size_t len = eoinput - input;
1269 char * pend = eodata + len;
1270
1271 int nnl = std::count(eodata, pend, '\n'); // newlines to be overwritten
1272 gcc_assert(0 == std::count(input, eoinput, '\n')); // newlines in input
1273
1274 memmove(eodata, input, len);
1275 nnl += std::count(pend, pend + nnl, '\n'); // other newlines to be overwritten
1276 std::fill(pend, pend + nnl, '\n');
1277
1278 eodata = pend;
1279
1280 #if LEXIO
1281 dbgmsg("%s:%3d: postcondition '%.*s'", __func__, __LINE__, int(size() + len) - 1, data);
1282 #endif
1283
1284 return eodata;
1285 }
1286
1287 const char * cobol_filename();
1288
1289 static filespan_t&
1290 mapped_file( FILE *input ) {
1291 static std::map<int, filespan_t> inputs;
1292
1293 int fd = fileno(input);
1294 gcc_assert(fd > 0);
1295
1296 filespan_t& mfile = inputs[fd];
1297 if( mfile.data ) {
1298 return mfile;
1299 }
1300
1301 struct stat sb;
1302 if( 0 != fstat(fd, &sb) ) {
1303 cbl_err( "%s: could not stat fd %d", __func__, fd );
1304 }
1305
1306 mfile.use_nada();
1307
1308 if( sb.st_size > 0 ) {
1309 static const int flags = MAP_PRIVATE;
1310
1311 void *p = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, flags, fd, 0);
1312 if( p == MAP_FAILED ) {
1313 cbl_err( "%s: could not map fd %d", __func__, fd );
1314 }
1315
1316 mfile.lineno_reset();
1317 mfile.data = mfile.cur = mfile.eol = mfile.eodata = static_cast<char*>(p);
1318 mfile.eodata += sb.st_size;
1319 }
1320 return mfile;
1321 }
1322
1323 char filespan_t::empty_file[8] = " \n";
1324
1325 static void unmap_file( filespan_t& mfile ) {
1326 if( ! mfile.nada() ) {
1327 munmap(mfile.data, mfile.size() - 1);
1328 }
1329 mfile = filespan_t();
1330 }
1331
1332 extern int yylineno;
1333
1334 static void
1335 print_lexer_input( const char *buf, const char *ebuf ) {
1336 const char *eol, *lexio = getenv("lexio");
1337 int i;
1338 static int nbuf = 1;
1339 static FILE *output = NULL;
1340
1341 if( !lexio ) return;
1342 if( !output ) {
1343 output = fopen( lexio, "w" );
1344 if( !output ) output = stderr;
1345 }
1346
1347 fprintf( output, "*> buffer %d\n", nbuf );
1348 for( i = 0, eol = std::find(buf, ebuf, '\n');
1349 eol != ebuf; buf = eol, eol = std::find(buf, ebuf, '\n'), i++ ) {
1350 eol++;
1351 fprintf( output, "%5d %.*s", yylineno + i, int(eol - buf), buf );
1352 }
1353 if( buf < ebuf ) {
1354 fprintf( output, "%5d %.*s", yylineno + i, int(eol - buf), buf );
1355 }
1356 fprintf( output, "*> endbuf %d\n", nbuf++ );
1357 fflush(output);
1358 }
1359
1360 /*
1361 * Fill about as much of the lexer's buffer as possible, except skip
1362 * leading blanks on blank lines.
1363 */
1364 int
1365 lexer_input( char buf[], int max_size, FILE *input ) {
1366 filespan_t& mfile( mapped_file(input) );
1367
1368 if( mfile.cur == mfile.eodata ) {
1369 if( mfile.cur ) unmap_file(mfile);
1370 return 0;
1371 }
1372
1373 gcc_assert( mfile.data <= mfile.cur && mfile.cur < mfile.eodata );
1374
1375 char *next = std::min(mfile.eodata, mfile.cur + max_size);
1376 buffer_t output(buf, buf + max_size); // initializes pos
1377
1378 // Fill output, keeping only NL for blank lines.
1379 for( auto p = mfile.cur; p < next; *output.pos++ = *p++ ) {
1380 static bool at_bol = false;
1381 if( at_bol ) {
1382 auto nonblank_l = std::find_if( p, next,
1383 []( char ch ) {
1384 return !isblank(ch); } );
1385 if( nonblank_l + 1 < next ) {
1386 if( *nonblank_l == '\r' ) nonblank_l++; // Windows
1387 if( *nonblank_l == '\n' ) {
1388 p = nonblank_l;
1389 continue;
1390 }
1391 }
1392 }
1393 at_bol = *p == '\n';
1394 }
1395
1396 gcc_assert( output.pos <= output.eodata );
1397 output.eodata = output.pos;
1398
1399 mfile.cur = next;
1400 gcc_assert(mfile.cur <= mfile.eodata);
1401
1402 // Buffer full or input exhausted.
1403 print_lexer_input(output.data, output.eodata);
1404
1405 return output.size();
1406 }
1407
1408 static const char *
1409 find_filter( const char filter[] ) {
1410
1411 if( 0 == access(filter, X_OK) ) {
1412 return filter;
1413 }
1414
1415 const char *path = getenv("PATH");
1416 if( ! path ) return NULL;
1417 char *p = xstrdup(path), *eopath = p + strlen(p);
1418
1419 while( *p != '\0' ) {
1420 auto pend = std::find( p, eopath, ':' );
1421 if( *pend == ':' ) *pend++ = '\0';
1422
1423 char *name = xasprintf( "%s/%s", p, filter );
1424
1425 if( 0 == access(name, X_OK) ) {
1426 return name;
1427 }
1428 p = pend;
1429 }
1430 return NULL;
1431 }
1432
1433 bool verbose_file_reader = false;
1434
1435 typedef std::pair <char *, std::list<std::string> > preprocessor_filter_t;
1436 static std::list<preprocessor_filter_t> preprocessor_filters;
1437 static std::list<const char *> included_files;
1438
1439 /*
1440 * Keep a list of files added with -include on the command line.
1441 */
1442 bool
1443 include_file_add(const char filename[]) {
1444 struct stat sb;
1445 if( -1 == stat(filename, &sb) ) return false;
1446 included_files.push_back(filename);
1447 return true;
1448 }
1449
1450 bool
1451 preprocess_filter_add( const char input[] ) {
1452 std::list <std::string> options;
1453 std::string filter(input);
1454 size_t pos = filter.find(",");
1455
1456 if( pos != filter.npos ) {
1457 std::vector<char> others( filter.size() - pos, '\0' );
1458 std::copy( filter.begin() + pos + 1, filter.end(), others.begin() );
1459 filter.resize(pos);
1460 char *optstr = others.data();
1461 for( char *opt = optstr + 1; (opt = strtok(opt, ",")); opt = NULL ) {
1462 options.push_back(opt);
1463 }
1464 }
1465
1466 auto filename = find_filter(filter.c_str());
1467 if( !filename ) {
1468 yywarn("preprocessor '%s/%s' not found", getcwd(NULL, 0), filter.c_str());
1469 return false;
1470 }
1471 preprocessor_filters.push_back( std::make_pair(xstrdup(filename), options) );
1472 return true;
1473 }
1474
1475 void
1476 cdftext::echo_input( int input, const char filename[] ) {
1477 int fd;
1478 if( -1 == (fd = dup(input)) ) {
1479 yywarn( "could not open preprocessed file %s to echo to standard output",
1480 filename );
1481 return;
1482 }
1483
1484 auto mfile = map_file(fd);
1485
1486 if( -1 == write(STDOUT_FILENO, mfile.data, mfile.size()) ) {
1487 yywarn( "could not write preprocessed file %s to standard output",
1488 filename );
1489 }
1490 if( -1 == munmap(mfile.data, mfile.size()) ) {
1491 yywarn( "could not release mapped file" );
1492 }
1493 if( -1 == close(fd) ) {
1494 yywarn( "could not close mapped file" );
1495 }
1496 }
1497
1498 static inline ino_t
1499 inode_of( int fd ) {
1500 struct stat sb;
1501 if( -1 == fstat(fd, &sb) ) {
1502 cbl_err( "could not stat fd %d", fd);
1503 }
1504 return sb.st_ino;
1505 }
1506
1507 FILE *
1508 cdftext::lex_open( const char filename[] ) {
1509 int input = open_input( filename );
1510 if( input == -1 ) return NULL;
1511
1512 int output = open_output();
1513
1514 // Process any files supplied by the -include command-line option.
1515 for( auto name : included_files ) {
1516 if( -1 == (input = open(name, O_RDONLY)) ) {
1517 yyerrorvl(1, "", "cannot open -include file %s", name);
1518 continue;
1519 }
1520 cobol_filename(name, inode_of(input));
1521 filespan_t mfile( free_form_reference_format( input ) );
1522
1523 process_file( mfile, output );
1524
1525 cobol_filename_restore(); // process_file restores only for COPY
1526 }
1527 included_files.clear();
1528
1529 cobol_filename(filename, inode_of(input));
1530 filespan_t mfile( free_form_reference_format( input ) );
1531
1532 process_file( mfile, output );
1533
1534 if( lexer_echo() ) {
1535 echo_input(output, filename);
1536 }
1537
1538 for( auto filter_pair : preprocessor_filters ) {
1539 input = output;
1540 output = open_output();
1541
1542 char *filter = filter_pair.first;
1543 std::list<std::string>& options = filter_pair.second;
1544
1545 std::vector <char*> argv(2 + options.size(), NULL);
1546 argv[0] = filter;
1547
1548 auto last_argv = std::transform( options.begin(), options.end(), argv.begin() + 1,
1549 []( const std::string& opt ) {
1550 return xstrdup(opt.c_str());
1551 } );
1552 *last_argv = NULL;
1553
1554 pid_t pid = fork();
1555
1556 switch(pid){
1557 case -1: cbl_err( "%s", __func__);
1558 break;
1559 case 0: // child
1560 if( -1 == dup2(input, STDIN_FILENO) ) {
1561 cbl_err( "%s: could not dup input", __func__);
1562 }
1563 if( -1 == dup2(output, STDOUT_FILENO) ) {
1564 cbl_err( "%s: could not dup output", __func__);
1565 }
1566 if( -1 == lseek(STDIN_FILENO, SEEK_SET, 0) ) {
1567 cbl_err( "%s: could not seek to start of file", __func__);
1568 }
1569 int erc;
1570 if( -1 == (erc = execv(filter, argv.data())) ) {
1571 yywarn("could not execute %s", filter);
1572 }
1573 _exit(erc);
1574 }
1575 int status;
1576 auto kid = wait(&status);
1577 gcc_assert(pid == kid);
1578 if( kid == -1 ) cbl_err( "failed waiting for pid %ld", static_cast<long>(pid));
1579
1580 if( WIFSIGNALED(status) ) {
1581 cbl_errx( "%s pid %ld terminated by %s",
1582 filter, static_cast<long>(kid), strsignal(WTERMSIG(status)) );
1583 }
1584 if( WIFEXITED(status) ) {
1585 if( (status = WEXITSTATUS(status)) != 0 ) {
1586 cbl_errx( "%s exited with status %d",
1587 filter, status);
1588 }
1589 }
1590 yywarn( "applied %s", filter );
1591 }
1592
1593 return fdopen( output, "r");
1594 }
1595
1596 int
1597 cdftext::open_input( const char filename[] ) {
1598 int fd = open(filename, O_RDONLY);
1599 if( fd == -1 ) {
1600 dbgmsg( "could not open '%s': %s", filename, xstrerror(errno) );
1601 }
1602
1603 verbose_file_reader = NULL != getenv("GCOBOL_TEMPDIR");
1604
1605 if( verbose_file_reader ) {
1606 yywarn("verbose: opening %s for input", filename);
1607 }
1608 return fd;
1609 }
1610
1611 int
1612 cdftext::open_output() {
1613 char *name = getenv("GCOBOL_TEMPDIR");
1614
1615 if( name && 0 != strcmp(name, "/") ) {
1616 int fd;
1617 char * stem = xasprintf("%sXXXXXX", name);
1618 if( -1 == (fd = mkstemp(stem)) ) {
1619 cbl_err( "could not open temporary file '%s' (%s)",
1620 name, realpath(name, stem));
1621 }
1622 return fd;
1623 }
1624
1625 FILE *fh = tmpfile();
1626 if( !fh ) {
1627 cbl_err("could not create temporary file");
1628 }
1629
1630 return fileno(fh);
1631 }
1632
1633 filespan_t
1634 cdftext::map_file( int fd ) {
1635 gcc_assert(fd > 0);
1636
1637 filespan_t mfile;
1638 mfile.use_nada();
1639
1640 struct stat sb;
1641 do {
1642 if( 0 != fstat(fd, &sb) ) {
1643 cbl_err( "%s: could not stat fd %d", __func__, fd );
1644 }
1645 if( S_ISFIFO(sb.st_mode) ) {
1646 // Copy FIFO to regular file that can be mapped.
1647 int input = open_output();
1648 std::swap(fd, input); // fd will continue to be the input
1649 static char block[4096 * 4];
1650 ssize_t n;
1651 while( (n = read(input, block, sizeof(block))) != 0 ) {
1652 ssize_t nout = write(fd, block, n);
1653 if( nout != n ) {
1654 cbl_err( "%s: could not prepare map file from FIFO %d",
1655 __func__, input);
1656 }
1657 if( false ) dbgmsg("%s: copied " HOST_SIZE_T_PRINT_DEC " bytes from FIFO",
1658 __func__, (fmt_size_t)nout);
1659 }
1660 }
1661 } while( S_ISFIFO(sb.st_mode) );
1662
1663 if( sb.st_size > 0 ) {
1664 static const int flags = MAP_PRIVATE;
1665
1666 void *p = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, flags, fd, 0);
1667 if( p == MAP_FAILED ) {
1668 cbl_err( "%s: could not map fd %d", __func__, fd );
1669 }
1670
1671 mfile.lineno_reset();
1672 mfile.data = mfile.cur = mfile.eol = mfile.eodata = static_cast<char*>(p);
1673 mfile.eodata += sb.st_size;
1674 }
1675
1676 return mfile;
1677 }
1678
1679 bool lexio_dialect_mf();
1680
1681 /*
1682 * A valid sequence area is 6 digits or blanks at the begining of the line that
1683 * contains PROGRAM-ID. Return NULL if no valid sequence area, else return
1684 * pointer to BOL.
1685 */
1686 static const char *
1687 valid_sequence_area( const char *data, const char *eodata ) {
1688
1689 for( const char *p = data;
1690 (p = std::find_if(p, eodata, is_p)) != eodata;
1691 p++ )
1692 {
1693 auto eol = std::find(p, eodata, '\n');
1694 if( p == data || ISSPACE(p[-1]) ) {
1695 if( is_program_id(p, eol) ) { // found program-id token
1696 const char *bol = p;
1697 for( ; data <= bol-1 && bol[-1] != '\n'; --bol )
1698 ;
1699 if( 6 < p - bol ) {
1700 if( std::all_of(bol, bol+6, ::isdigit) ) {
1701 return bol;
1702 }
1703 if( std::all_of(bol, bol+6, ::isblank) ) {
1704 return bol;
1705 }
1706 break;
1707 }
1708 }
1709 }
1710 }
1711 return nullptr;
1712 }
1713
1714 /*
1715 * Reference Format -- valid COBOL between columns 8 and 72 -- has data after
1716 * column 72 on the PROGRAM-ID line. Extended Reference Format (that allows
1717 * longer lines) has no reason to follow the PROGRAM-ID with more stuff.
1718 */
1719 static bool
1720 infer_reference_format( const char *bol, const char *eodata ) {
1721 assert(bol);
1722 auto eol = std::find(bol, eodata, '\n');
1723 if( 72 < eol - bol ) {
1724 return ! std::all_of(bol + 72, eol, ::isspace);
1725 }
1726 return false;
1727 }
1728
1729 filespan_t
1730 cdftext::free_form_reference_format( int input ) {
1731 filespan_t source_buffer = map_file(input);
1732 filespan_t mfile(source_buffer);
1733
1734 /*
1735 * current_line_t describes the segment of mapped file that is the
1736 * "current line" being processed. Its only use is for line
1737 * continuation, whether string literals or not.
1738 */
1739 struct current_line_t {
1740 size_t lineno;
1741 bytespan_t line;
1742 // construct with length zero
1743 explicit current_line_t( char data[] ) : lineno(0), line(data, data) {}
1744 } current( mfile.data );
1745
1746 /*
1747 * Infer source code format.
1748 */
1749 if( cdf_source_format().inference_pending() ) {
1750 const char *bol = valid_sequence_area(mfile.data, mfile.eodata);
1751 if( bol ) {
1752 cdf_source_format().infer( bol, infer_reference_format(bol, mfile.eodata) );
1753 }
1754 }
1755
1756 while( mfile.next_line() ) {
1757 check_push_pop_directive(mfile);
1758 check_source_format_directive(mfile);
1759 remove_inline_comment(mfile.cur, mfile.eol);
1760
1761 if( mfile.is_blank_line() ) continue;
1762
1763 char *indcol = indicated(mfile.cur, mfile.eol); // true only for fixed
1764 // // format
1765
1766 if( is_fixed_format() && !indcol ) { // short line
1767 erase_source(mfile.cur, mfile.eol);
1768 }
1769
1770 if( indcol ) {
1771 // Set to blank columns 1-6 and anything past the right margin.
1772 erase_source(mfile.cur, indcol);
1773 if( is_reference_format() ) {
1774 if( mfile.cur + right_margin() < mfile.eol ) {
1775 auto p = std::find(mfile.cur + right_margin(), mfile.eol, '\n');
1776 erase_source(mfile.cur + right_margin(), p);
1777 }
1778 }
1779
1780 switch( TOUPPER(*indcol) ) {
1781 case '-':
1782 gcc_assert(0 < current.line.size());
1783 /*
1784 * The "current line" -- the line being continued -- may be many
1785 * lines earlier (with many intervening newlines) or may intrude
1786 * on its succeeding line. Erase the continuation line.
1787 */
1788 {
1789 char *pend = mfile.eol;
1790 if( right_margin() ) {
1791 pend = std::min(mfile.cur + right_margin(), mfile.eol);
1792 }
1793 // The appended segment has no newline because the erased line retains
1794 // one.
1795 pend = std::find(indcol + 1, pend, '\n');
1796 char *p = current.line.append(indcol + 1, pend );
1797 if( (p = std::max(p, mfile.cur)) < mfile.eol ) {
1798 erase_source(p, mfile.eol);
1799 }
1800 }
1801 continue;
1802 case SPACE:
1803 break;
1804 case 'D':
1805 /*
1806 * Pass the D to the lexer, because WITH DEBUGGING MODE is
1807 * parsed in the parser. This assumes too strict a rule: that
1808 * all the source is in one format. In fact, DEBUGGING MODE
1809 * could be set on, and >>SOURCE-FORMAT can switch back and
1810 * forth. To solve that, we'd have to parse WITH DEBUGGING MODE
1811 * in free_form_reference_format(), which is a lot of work for
1812 * an obsolete feature.
1813 */
1814 break;
1815 case '*':
1816 case '/':
1817 if( indcol < mfile.eol - 1 ) {
1818 erase_source(indcol, mfile.eol);
1819 }
1820 continue;
1821 case '$':
1822 if( lexio_dialect_mf() ) {
1823 break;
1824 }
1825 __attribute__ ((fallthrough));
1826 default: // flag other characters in indicator area
1827 if( ! ISSPACE(indcol[0]) ) {
1828 yyerrorvl( mfile.lineno(), cobol_filename(),
1829 "error: stray indicator '%c' (0x%x): \"%.*s\"",
1830 indcol[0], indcol[0],
1831 int(mfile.line_length() - 1), mfile.cur );
1832 *indcol = SPACE;
1833 }
1834 break;
1835 }
1836 }
1837 current.line.update(mfile.cur, mfile.eol, right_margin());
1838 current.lineno = mfile.lineno();
1839 } // next line
1840
1841 return source_buffer;
1842 }
1843
1844 /*
1845 * process_file is a recursive routine that opens and processes
1846 * included files. It uses the input file stack in two ways: to check
1847 * copybook uniqueness, and (via the lexer) to keep track filenames
1848 * and line numbers.
1849 *
1850 * When reading copybook files, the copybook object enforces the rule
1851 * that no copybook may include itself, even indirectly. It does that
1852 * by relying on the unique_stack to deny a push. Because the reader
1853 * makes no attempt to count lines, line numbers in the input stack
1854 * are all 1 at this point.
1855 *
1856 * When returning from the top-level recursion, the input stack has
1857 * the original file's name on top, with depth 1. At that point, the
1858 * lexer begins tokenizing the input.
1859 *
1860 * The input stream sent to the lexer is delimited by #FILE tokens
1861 * denoting the source filename. As far as the lexer is concerned,
1862 * there's only ever one file: the name passed to lex_open() when we
1863 * kicked things off. But messages and the debugger need to know
1864 * which file and line each statment appeared in.
1865 *
1866 * The lexer uses the input stack to keep track of names and
1867 * numbers. The top of the input file stack is the current file
1868 * context, initially set to line 1. When the lexer sees a push, it
1869 * updates the top-of-stack with the current line number, yylineno,
1870 * and then pushes the copybook filename with line 1. When it sees a
1871 * pop, the current file is popped, of course; its line number no
1872 * longer matters. Then the top-of-stack is used to update the current
1873 * cobol filename and yylineno.
1874 */
1875 void
1876 cdftext::process_file( filespan_t mfile, int output, bool second_pass ) {
1877 static size_t nfiles = 0;
1878
1879 __gnu_cxx::stdio_filebuf<char> outbuf(fdopen(output, "a"), std::ios::out);
1880 std::ostream out(&outbuf);
1881 std::ostream_iterator<char> ofs(out);
1882
1883 // indicate current file
1884 static const char file_push[] = "\f#FILE PUSH ", file_pop[] = "\f#FILE POP\f";
1885
1886 if( !included_files.empty() ) { ++nfiles; }; // force push/pop of included filename
1887 if( !second_pass && nfiles++ ) {
1888 static const char delimiter[] = "\f";
1889 const char *filename = cobol_filename();
1890 std::copy(file_push, file_push + strlen(file_push), ofs);
1891 std::copy(filename, filename + strlen(filename), ofs);
1892 std::copy(delimiter, delimiter + strlen(delimiter), ofs);
1893 out.flush();
1894 }
1895
1896 // parse CDF directives
1897 while( mfile.next_line() ) {
1898 yylloc = mfile.as_location();
1899 auto copied = parse_copy_directive(mfile);
1900 if( copied.parsed && copied.fd != -1 ) {
1901 gcc_assert(copied.erased_lines.p);
1902 std::copy_if(copied.erased_lines.p, copied.erased_lines.pend, ofs,
1903 []( char ch ) { return ch == '\n'; } );
1904 struct { int in, out; filespan_t mfile; } copy;
1905 dbgmsg("%s:%d: line " HOST_SIZE_T_PRINT_UNSIGNED ", opening %s on fd %d",
1906 __func__, __LINE__, (fmt_size_t)mfile.lineno(),
1907 copybook.source(), copybook.current()->fd);
1908 copy.in = copybook.current()->fd;
1909 copy.mfile = free_form_reference_format( copy.in );
1910
1911 if( copied.partial_line.size() ) {
1912 std::copy(copied.partial_line.p, copied.partial_line.pend, ofs);
1913 }
1914 out.flush();
1915
1916 if( copied.nreplace == 0 ) {
1917 // process with extant REPLACE directive
1918 process_file(copy.mfile, output);
1919 } else {
1920 copy.out = open_output();
1921 // process to intermediate, applying COPY ... REPLACING
1922 process_file(copy.mfile, copy.out);
1923 copy.mfile = map_file(copy.out);
1924 replace_directives.pop();
1925 // process intermediate with extant REPLACE directive
1926 process_file(copy.mfile, output, true);
1927 // COPY statement is erased from input if processed successfully
1928 }
1929 cobol_filename_restore();
1930 }
1931
1932 auto erased = parse_replace_directive(mfile);
1933 if( erased.p ) {
1934 std::copy_if( erased.p, erased.pend, ofs,
1935 []( char ch ) { return ch == '\n'; } );
1936 }
1937 if( replace_directives.empty() ) {
1938 std::copy(mfile.cur, mfile.eol, ofs);
1939 continue; // No active REPLACE directive.
1940 }
1941
1942 std::list<span_t> segments = segment_line(mfile);
1943
1944 for( const auto& segment : segments ) {
1945 std::copy(segment.p, segment.pend, ofs);
1946 }
1947
1948 out.flush();
1949 }
1950 // end of file
1951 if( !second_pass && --nfiles ) {
1952 std::copy(file_pop, file_pop + strlen(file_pop), ofs);
1953 out.flush();
1954 }
1955 if( !included_files.empty() ) { --nfiles; };
1956 }
1957
1958 std::list<span_t>
1959 cdftext::segment_line( filespan_t& mfile ) {
1960 std::list<span_t> output;
1961
1962 gcc_assert( ! replace_directives.empty() );
1963 std::list<replace_t> pending;
1964 recognize_replacements( mfile, pending );
1965
1966 if( pending.empty() ) {
1967 output.push_back( span_t(mfile.cur, mfile.eol) );
1968 return output;
1969 }
1970
1971 /*
1972 * If the replacement changes the number of lines in the replaced text, we
1973 * need to reset the line number, because the next statement is on a
1974 * different line in the manipulated text than in the original. Before each
1975 * replacement, set the original line number. After each replacement, set
1976 * the line number after the elided text on the next line.
1977 */
1978 for( const replace_t& segment : pending ) {
1979 gcc_assert(mfile.cur <= segment.before.p);
1980 gcc_assert(segment.before.pend <= mfile.eodata);
1981
1982 struct { unsigned long ante, post; } lineno = {
1983 gb4(mfile.lineno()), gb4(mfile.lineno() + segment.after.nlines())
1984 };
1985 const char *directive = lineno.ante == lineno.post?
1986 nullptr : xasprintf("\n#line %lu \"%s\"\n",
1987 lineno.ante, cobol_filename());
1988
1989 if( directive )
1990 output.push_back( span_t(strlen(directive), directive) );
1991 output.push_back( span_t(mfile.cur, segment.before.p) );
1992 output.push_back( span_t(segment.after.p, segment.after.pend ) );
1993 if( directive )
1994 output.push_back( span_t(strlen(directive), directive) );
1995
1996 mfile.cur = const_cast<char*>(segment.before.pend);
1997 }
1998
1999 if( mfile.eol < mfile.cur ) {
2000 if( (mfile.eol = std::find(mfile.cur, mfile.eodata, '\n')) < mfile.eodata ) {
2001 mfile.eol++;
2002 }
2003 }
2004
2005 // last segment takes to EOL
2006 output.push_back( span_t(mfile.cur, mfile.eol) );
2007
2008 return output;
2009 }