Debian Codegraph @

gcc/cobol/util.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 /*
32 * This file supports parsing without requiring access to the symbol
33 * table definition. Unlike the Bison input, this file brings in gcc
34 * header files.
35 */
36
37 #include <cobol-system.h>
38 #include <coretypes.h>
39 #include <tree.h>
40 #undef yy_flex_debug
41
42 #include <langinfo.h>
43
44 #include <coretypes.h>
45 #include <version.h>
46 #include <demangle.h>
47 #include <intl.h>
48 #include <backtrace.h>
49 #include <diagnostic.h>
50 #include <diagnostic-color.h>
51 #include <diagnostic-url.h>
52 #include <diagnostic-metadata.h>
53 #include <diagnostic-path.h>
54 #include <edit-context.h>
55 #include <selftest.h>
56 #include <selftest-diagnostic.h>
57 #include <opts.h>
58
59 #include "util.h"
60
61 #include "cbldiag.h"
62 #include "cdfval.h"
63 #include "lexio.h"
64
65 #include "../../libgcobol/ec.h"
66 #include "../../libgcobol/common-defs.h"
67 #include "symbols.h"
68 #include "inspect.h"
69 #include "../../libgcobol/io.h"
70 #include "genapi.h"
71 #include "genutil.h"
72
73 #pragma GCC diagnostic ignored "-Wunused-result"
74 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
75
76 // External declarations.
77 extern FILE * yyin;
78 extern int yyparse(void);
79
80 extern int demonstration_administrator(int N);
81
82 #if !defined (HAVE_GET_CURRENT_DIR_NAME)
83 /* Posix platforms might not have get_current_dir_name but should have
84 getcwd() and PATH_MAX. */
85 #if __has_include (<limits.h>)
86 # include <limits.h>
87 #endif
88 /* The Hurd doesn't define PATH_MAX. */
89 #if !defined (PATH_MAX) && defined(__GNU__)
90 # define PATH_MAX 4096
91 #endif
92 static inline char *
93 get_current_dir_name ()
94 {
95 /* Use libiberty's allocator here. */
96 char *buf = static_cast<char *>(xmalloc (PATH_MAX));
97 return getcwd (buf, PATH_MAX);
98 }
99 #endif
100
101 /*
102 * For printing messages, usually the size of the thing is some kind of string
103 * length, and doesn't really need a size_t. For message formatting, use a
104 * simple unsigned long, and warn if that's no good. "gb4" here stands for
105 * "4 Gigabytes".
106 */
107 unsigned long
108 gb4( size_t input ) {
109 if( input != static_cast<unsigned long>(input) ) {
110 yywarn("size too large to print: %lx:%lx",
111 (unsigned long)(input >> (4 * sizeof(unsigned long))),
112 static_cast<unsigned long>(input));
113 }
114 return input;
115 }
116
117 /*
118 * Most CDF Directives -- those that have state -- can be pushed and popped.
119 * This class maintains stacks of them, with each stack having a "default
120 * value" that may be updated, without push/pop, via a CDF directive or
121 * command-line option. A push to a stack pushes the default value onto it; a
122 * pop copies the top of the stack to the default value.
123 *
124 * Supported:
125 * CALL-CONVENTION
126 * COBOL-WORDS
127 * DEFINE
128 * DISPLAY
129 * IF
130 * POP
131 * PUSH
132 * SOURCE FORMAT
133 * TURN
134 * not supported
135 * EVALUATE
136 * FLAG-02
137 * FLAG-14
138 * LEAP-SECOND
139 * LISTING
140 * PAGE
141 * PROPAGATE
142 * REF-MOD-ZERO-LENGTH
143 *
144 * >>PUSH ALL calls the class's push() method.
145 * >>POP ALL calls the class's pop() method.
146 */
147 class cdf_directives_t
148 {
149 template <typename T>
150 class cdf_stack_t : private std::stack<T> { // cppcheck-suppress noConstructor
151 T default_value;
152 const T& top() const { return std::stack<T>::top(); }
153 bool empty() const { return std::stack<T>::empty(); }
154 public:
155 void value( const T& value ) {
156 T& output( empty()? default_value : std::stack<T>::top() ); // cppcheck-suppress constVariableReference
157 output = value;
158 dbgmsg("cdf_directives_t::%s: %s", __func__, str(output).c_str());
159 }
160 T& value() {
161 return empty()? default_value : std::stack<T>::top();
162 }
163 void push() {
164 std::stack<T>::push(value());
165 dbgmsg("cdf_directives_t::%s: %s", __func__, str(top()).c_str());
166 }
167 void pop() {
168 if( empty() ) {
169 error_msg(YYLTYPE(), "CDF stack empty"); // cppcheck-suppress syntaxError
170 return;
171 }
172 default_value = top();
173 std::stack<T>::pop();
174 dbgmsg("cdf_directives_t::%s: %s", __func__, str(default_value).c_str());
175 }
176 protected:
177 static std::string str(cbl_call_convention_t arg) {
178 char output[2] = { static_cast<char>(arg) };
179 return std::string("call-convention ") + output;
180 }
181 static std::string str(current_tokens_t) {
182 return "<cobol-words>";
183 }
184 static std::string str(cdf_values_t) {
185 return "<dictionary>";
186 }
187 static std::string str(source_format_t arg) {
188 return arg.description();
189 }
190 static std::string str(cbl_enabled_exceptions_t) {
191 return "<enabled_exceptions>";
192 }
193 };
194
195 public:
196 cdf_stack_t<cbl_call_convention_t> call_convention;
197 cdf_stack_t<current_tokens_t> cobol_words;
198 cdf_stack_t<cdf_values_t> dictionary; // DEFINE
199 cdf_stack_t<source_format_t> source_format;
200 cdf_stack_t<cbl_enabled_exceptions_t> enabled_exceptions;
201
202 cdf_directives_t() {
203 call_convention.value() = cbl_call_cobol_e;
204 }
205
206 void push() {
207 call_convention.push();
208 cobol_words.push();
209 dictionary.push();
210 source_format.push();
211 enabled_exceptions.push();
212 }
213 void pop() {
214 call_convention.pop();
215 cobol_words.pop();
216 dictionary.pop();
217 source_format.pop();
218 enabled_exceptions.pop();
219 }
220 };
221 static cdf_directives_t cdf_directives;
222
223 void
224 current_call_convention( cbl_call_convention_t convention) {
225 cdf_directives.call_convention.value(convention);
226 }
227 cbl_call_convention_t
228 current_call_convention() {
229 return cdf_directives.call_convention.value();
230 }
231
232 current_tokens_t&
233 cdf_current_tokens() {
234 return cdf_directives.cobol_words.value();
235 }
236
237 cdf_values_t&
238 cdf_dictionary() {
239 return cdf_directives.dictionary.value();
240 }
241
242 void
243 cobol_set_indicator_column( int column ) {
244 cdf_directives.source_format.value().indicator_column_set(column);
245 }
246 source_format_t& cdf_source_format() {
247 return cdf_directives.source_format.value();
248 }
249
250 cbl_enabled_exceptions_t&
251 cdf_enabled_exceptions() {
252 return cdf_directives.enabled_exceptions.value();
253 }
254
255 void cdf_push() { cdf_directives.push(); }
256 void cdf_push_call_convention() { cdf_directives.call_convention.push(); }
257 void cdf_push_current_tokens() { cdf_directives.cobol_words.push(); }
258 void cdf_push_dictionary() { cdf_directives.dictionary.push(); }
259 void cdf_push_enabled_exceptions() { cdf_directives.enabled_exceptions.push(); }
260 void cdf_push_source_format() { cdf_directives.source_format.push(); }
261
262 void cdf_pop() { cdf_directives.pop(); }
263 void cdf_pop_call_convention() { cdf_directives.call_convention.pop(); }
264 void cdf_pop_current_tokens() { cdf_directives.cobol_words.pop(); }
265 void cdf_pop_dictionary() { cdf_directives.dictionary.pop(); }
266 void cdf_pop_enabled_exceptions() { cdf_directives.enabled_exceptions.pop(); }
267 void cdf_pop_source_format() { cdf_directives.source_format.pop(); }
268
269 const char *
270 symbol_type_str( enum symbol_type_t type )
271 {
272 switch(type) {
273 case SymFilename:
274 return "SymFilename";
275 case SymField:
276 return "SymField";
277 case SymLabel:
278 return "SymLabel";
279 case SymSpecial:
280 return "SymSpecial";
281 case SymAlphabet:
282 return "SymAlphabet";
283 case SymFile:
284 return "SymFile";
285 case SymDataSection:
286 return "SymDataSection";
287 }
288 cbl_internal_error("%s:%d: invalid %<symbol_type_t%> %d", __func__, __LINE__, type);
289 return "???";
290 }
291
292 const char *
293 cbl_field_type_str( enum cbl_field_type_t type )
294 {
295 switch(type) {
296 case FldDisplay:
297 return "FldDisplay";
298 case FldInvalid:
299 return "Fld"; // Invalid";
300 case FldGroup:
301 return "FldGroup";
302 case FldAlphanumeric:
303 return "FldAlphanumeric";
304 case FldNumericBinary:
305 return "FldNumericBinary";
306 case FldFloat:
307 return "FldFloat";
308 case FldNumericBin5:
309 return "FldNumericBin5";
310 case FldPacked:
311 return "FldPacked";
312 case FldNumericDisplay:
313 return "FldNumericDisplay";
314 case FldNumericEdited:
315 return "FldNumericEdited";
316 case FldAlphaEdited:
317 return "FldAlphaEdited";
318 case FldLiteralA:
319 return "FldLiteralA";
320 case FldLiteralN:
321 return "FldLiteralN";
322 case FldClass:
323 return "FldClass";
324 case FldConditional:
325 return "FldConditional";
326 case FldForward:
327 return "FldForward";
328 case FldIndex:
329 return "FldIndex";
330 case FldSwitch:
331 return "FldSwitch";
332 case FldPointer:
333 return "FldPointer";
334 case FldBlob:
335 return "FldBlob";
336 }
337 cbl_internal_error("%s:%d: invalid %<symbol_type_t%> %d", __func__, __LINE__, type);
338 return "???";
339 }
340
341 const char *
342 cbl_logop_str( enum logop_t op )
343 {
344 switch(op) {
345 case not_op:
346 return "not_op";
347 case and_op:
348 return "and_op";
349 case or_op:
350 return "or_op";
351 case xor_op:
352 return "xor_op";
353 case xnor_op:
354 return "xnor_op";
355 case true_op:
356 return "true_op";
357 case false_op:
358 return "false_op";
359 }
360 dbgmsg("%s:%d: invalid logop_t %d", __func__, __LINE__, op);
361 return "???";
362 }
363
364 cbl_field_t
365 determine_intermediate_type( const cbl_refer_t& aref,
366 int op __attribute__ ((unused)),
367 const cbl_refer_t& bref )
368 {
369 cbl_field_t output = {};
370
371 if( aref.field->type == FldFloat || bref.field->type == FldFloat )
372 {
373 output.type = FldFloat;
374 output.data.capacity = 16;
375 output.attr = (intermediate_e );
376 }
377 else if( op == '*'
378 && aref.field->data.digits + bref.field->data.digits
379 > MAX_FIXED_POINT_DIGITS)
380 {
381 output.type = FldFloat;
382 output.data.capacity = 16;
383 output.attr = (intermediate_e );
384 }
385 else
386 {
387 output.type = FldNumericBin5;
388 output.data.capacity = 16;
389 output.data.digits = MAX_FIXED_POINT_DIGITS;
390 output.attr = (intermediate_e | signable_e );
391 }
392
393 return output;
394 }
395
396 static char regexmsg[80];
397
398 /*
399 * Scan part of the picture, parsing any repetition count.
400 */
401 int
402 repeat_count( const char picture[] )
403 {
404 char ch;
405 int n, count = -1;
406
407 n = sscanf( picture, "%c(%d)", &ch, &count );
408 if( count <= 0 && 4 < n ) { // parsed count is negative
409 count = 0; // zero is invalid; -1 means no repetition
410 }
411 return count;
412 }
413
414 const char *numed_message;
415
416 extern int yydebug, yy_flex_debug;
417
418 bool
419 is_alpha_edited( const char picture[] ) {
420 static const char valid[] = "abxABX90/(),.";
421 assert(picture);
422
423 for( const char *p = picture; *p != '\0'; p++ ) {
424 if( strchr(valid, *p) ) continue;
425 if( ISDIGIT(*p) ) continue;
426 if( symbol_decimal_point() == *p ) continue;
427 if( symbol_currency(*p) ) continue;
428
429 if( yydebug ) {
430 dbgmsg( "%s: bad character '%c' at %.*s<-- in '%s'",
431 __func__, *p, int(p - picture) + 1, picture, picture );
432 }
433 return false;
434 }
435 return true;
436 }
437
438 bool
439 is_numeric_edited( const char picture[] ) {
440 static const char valid[] = "BbPpVvZz90/(),.+-*"; // and CR DB
441 const char *p;
442 assert(picture);
443
444 if( strstr(picture, "(0)") ) {
445 numed_message = "'(0)' invalid in PICTURE (ISO 2023 13.18.40.3)";
446 return false;
447 }
448
449 // check for correct parenthetical constructs
450 for( p=picture; (p = strchr(p, '(')) != NULL; p++ ) {
451 int v, n, pos;
452 n = sscanf(++p, "%d%n", &v, &pos);
453 numed_message = NULL;
454
455 if( n == -1 ) {
456 numed_message = "invalid repeat-count in PICTURE";
457 } else if( n == 0 ) {
458 numed_message = "invalid repeat-count in PICTURE";
459 } else if( p[pos] != ')' ) {
460 numed_message = "unbalanced parentheses in PICTURE";
461 }
462 if( numed_message ) return false;
463 }
464 // check for dangling right parenthesis
465 for( p=picture; (p = strchr(p, ')')) != NULL; p++ ) {
466 auto prior = p;
467 while( picture < prior-- ) {
468 if( ISDIGIT(*prior) ) continue;
469 if( *prior == '(' ) break;
470 numed_message = "unbalanced parentheses in PICTURE";
471 return false;
472 }
473 }
474
475 if( (strchr(picture, 'Z') || strchr(picture, 'z')) && strchr(picture, '*') ) {
476 numed_message = "Z and * are mutually exclusive";
477 return false;
478 }
479
480 for( p = picture; *p != '\0'; p++ ) {
481 if( strchr(valid, *p) ) continue;
482 if( ISDIGIT(*p) ) continue;
483 if( symbol_decimal_point() == *p ) continue;
484 if( symbol_currency(*p) ) continue;
485
486 switch(*p) { // test for CR or DB
487 case 'C': case 'c':
488 if( TOUPPER(*++p) == 'R' ) continue;
489 numed_message = "expected CR in PICTURE";
490 break;
491 case 'D': case 'd':
492 if( TOUPPER(*++p) == 'B' ) continue;
493 numed_message = "expected DB in PICTURE";
494 break;
495 default:
496 numed_message = xasprintf("invalid PICTURE character "
497 "'%c' at offset " HOST_SIZE_T_PRINT_UNSIGNED
498 " in '%s'",
499 *p, (fmt_size_t)(p - picture), picture);
500 break;
501 }
502
503 dbgmsg( "%s: no, because '%c' at %.*s<-- in '%s'",
504 __func__, *p, int(p - picture) + 1, picture, picture );
505
506 return false;
507 }
508 return true;
509 }
510
511 char *
512 normalize_picture( char picture[] )
513 {
514 int erc;
515 char *p;
516
517 regex_t *preg = NULL;
518 const char regex[] = "([AX9])[(]([[:digit:]]+)[)]";
519 int cflags = REG_EXTENDED | REG_ICASE;
520 regmatch_t pmatch[4];
521
522 if( (erc = regcomp(preg, regex, cflags)) != 0 ) {
523 regerror(erc, preg, regexmsg, sizeof(regexmsg));
524 dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
525 return picture;
526 }
527
528 while( (erc = regexec(preg, picture, COUNT_OF(pmatch), pmatch, 0)) == 0 ) {
529 assert(pmatch[1].rm_so != -1 && pmatch[1].rm_so < pmatch[1].rm_eo);
530 size_t len = pmatch[1].rm_eo - pmatch[1].rm_so;
531 assert(len == 1);
532 const char *start = picture + pmatch[1].rm_so;
533
534 assert(pmatch[2].rm_so != -2 && pmatch[2].rm_so < pmatch[2].rm_eo);
535 len = pmatch[2].rm_eo - pmatch[2].rm_so;
536 assert(len > 0);
537
538 /*
539 * Overwrite e.g. A(4) with AAAA.
540 */
541 assert(pmatch[2].rm_so == pmatch[1].rm_eo + 1); // character paren number
542 p = picture + pmatch[2].rm_so;
543 len = 0;
544 fmt_size_t lenf = 0;
545 if( 1 != sscanf(p, "%" GCC_PRISZ "u", &lenf) ) {
546 dbgmsg("%s:%d: no number found in '%s'", __func__, __LINE__, p);
547 goto irregular;
548 }
549 len = lenf;
550 if( len == 0 ) {
551 dbgmsg("%s:%d: ZERO length found in '%s'", __func__, __LINE__, p);
552 goto irregular;
553 }
554
555 std::vector <char> pic(len + 1, '\0');
556 memset(pic.data(), *start, len);
557 const char *finish = picture + pmatch[2].rm_eo,
558 *eopicture = picture + strlen(picture);
559
560 p = xasprintf( "%*s%s%*s",
561 (int)(start - picture), picture,
562 pic.data(),
563 (int)(eopicture - finish), finish );
564
565 free(picture);
566 picture = p;
567 }
568 assert(erc == REG_NOMATCH);
569
570 irregular:
571 regfree(preg);
572
573 return picture;
574 }
575
576 static bool
577 memall( const char picture[], char ch )
578 {
579 for( const char *p=picture; *p != '\0'; p++ ) {
580 if( *p != ch ) {
581 return false;
582 }
583 }
584 return true;
585 }
586
587 static const char *
588 match( const char picture[], const char pattern[] )
589 {
590 int erc;
591
592 regex_t *preg = NULL;
593 int cflags = REG_EXTENDED;
594 regmatch_t pmatch[1];
595
596 if( (erc = regcomp(preg, pattern, cflags)) != 0 ) {
597 regerror(erc, preg, regexmsg, sizeof(regexmsg));
598 dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
599 return picture;
600 }
601
602 if( (erc = regexec(preg, picture, COUNT_OF(pmatch), pmatch, 0)) != 0 ) {
603 assert(erc == REG_NOMATCH);
604 return NULL;
605 }
606 assert(pmatch[0].rm_so != -1);
607 return picture + pmatch[0].rm_so;
608 }
609
610 bool
611 is_elementary( enum cbl_field_type_t type )
612 {
613 switch(type) {
614 case FldDisplay:
615 case FldInvalid:
616 case FldGroup:
617 case FldLiteralA:
618 case FldLiteralN:
619 case FldClass:
620 case FldConditional:
621 case FldForward:
622 case FldIndex:
623 case FldSwitch:
624 case FldBlob:
625 return false;
626 case FldPointer:
627 case FldAlphanumeric:
628 case FldPacked:
629 case FldNumericDisplay:
630 case FldNumericEdited:
631 case FldAlphaEdited:
632 case FldNumericBinary:
633 case FldNumericBin5:
634 case FldFloat:
635 return true; // takes up space
636 }
637 cbl_internal_error("%s:%d: invalid %<symbol_type_t%> %d", __func__, __LINE__, type);
638 return false;
639 }
640
641 static bool
642 is_numericish( cbl_field_type_t type ) {
643 return
644 type == FldNumericDisplay ||
645 type == FldNumericEdited || is_numeric(type);
646 }
647
648 static inline bool
649 is_numericish( const struct cbl_field_t *field ) {
650 return is_numericish(field->type);
651 }
652
653 static bool
654 integer_move_ok( const cbl_field_t *src, const cbl_field_t *tgt ) {
655 if( is_numericish(src) &&
656 ! (tgt->type == FldInvalid || is_literal(tgt)) ) {
657 if( src->data.rdigits > 0 ) {
658 dbgmsg("%s has %d rdigits", src->name, src->data.rdigits);
659 }
660 return src->data.rdigits == 0;
661 }
662 return integer_move_ok( tgt, src );
663 }
664
665 static bool
666 is_alphanumeric( const cbl_field_t *field ) {
667 assert(field);
668
669 if( is_elementary(field->type) ) {
670 switch(field->type) {
671 case FldAlphanumeric:
672 case FldPacked:
673 case FldNumericDisplay:
674 case FldNumericEdited:
675 case FldAlphaEdited:
676 case FldNumericBinary:
677 return true;
678 case FldNumericBin5:
679 case FldFloat:
680 return false;
681 default:
682 break;
683 }
684 return false;
685 }
686
687 if( field->type != FldGroup ) return false;
688
689 const struct symbol_elem_t *e = symbol_elem_of(field);
690
691 for( ++e; e < symbols_end(); e++ ) {
692 if( e->type != SymField ) {
693 // Ignore non-fields:
694 continue;
695 }
696 const uint32_t level = cbl_field_of(e)->level;
697 if( level == 88 ) continue;
698 if( level <= field->level || level == LEVEL77 ) {
699 break; // stop if next field is higher in the hierarchy
700 }
701
702 if( ! is_alphanumeric(cbl_field_of(e)) ) {
703 return false;
704 }
705 }
706 return true;
707 }
708
709 /*
710 * When setting a field's type, there is a 3-way test involving:
711 * 1. The current value of cbl_field_t::type
712 * 2. The value of cbl_field_t::usage, from USAGE or parent's USAGE
713 * 3. The candidate (proposed new type)
714 *
715 * cbl_field_t::usage == FldInvalid indicates no prescribed
716 * type. Type-setting succeeds unless the candidate cannot override
717 * the current type.
718 *
719 * A candidate of FldDisplay updates cbl_field_t::usage only, and only
720 * if it is FldInvalid, provided the cbl_field_t::type is either
721 * FldInvalid or displayable. FldDisplay isn't really a type, but a
722 * kind of type: it constrains what the type may be set to.
723 *
724 * When cbl_field_t::usage == FldDisplay, the candidate type must be
725 * displayable, else the update is rejected.
726 *
727 * If the candidate passes the usage test, we consider the current type.
728 *
729 * cbl_field_t::type == FldInvalid indicates no defined type
730 * (yet). The candidate type becomes the type. Otherwise, the
731 * candidate must match the type, or can override it.
732 */
733 static bool
734 is_displayable( cbl_field_type_t type ) {
735 switch(type) {
736 case FldDisplay:
737 case FldAlphaEdited:
738 case FldAlphanumeric:
739 case FldNumericDisplay:
740 case FldNumericEdited:
741 return true;
742 default: break;
743 }
744 return false;
745 }
746
747 // disallow implausible combinations
748 static bool
749 plausible_usage( cbl_field_type_t usage, cbl_field_type_t candidate ) {
750 switch(usage) {
751 case FldInvalid:
752 return true;
753 case FldDisplay:
754 return is_displayable(candidate);
755 case FldGroup:
756 gcc_unreachable();
757 default:
758 if( candidate == FldDisplay ) return false; // because overrides FldInvalid only
759 break;
760 }
761
762 assert(is_elementary(usage));
763 assert(is_elementary(candidate));
764 return usage == candidate || (is_numericish(usage) && is_numericish(candidate));
765 }
766
767 cbl_field_t *
768 symbol_field_index_set( cbl_field_t *field ) {
769 static const cbl_field_data_t data { 0, 8 };
770
771 field->data = data;
772
773 field->type = FldIndex;
774 field->attr &= ~size_t(signable_e);
775
776 return field;
777 }
778
779 bool
780 symbol_field_type_update( cbl_field_t *field,
781 cbl_field_type_t candidate, bool is_usage ) {
782
783 if( is_usage && (candidate == FldIndex || candidate == FldPointer) ) {
784 field->usage = candidate;
785 switch(field->type) {
786 case FldInvalid:
787 case FldIndex:
788 case FldPointer:
789 // set the type
790 field->type = candidate;
791 if( field->data.capacity == 0 ) {
792 static const cbl_field_data_t data = {0, 8, 0, 0, NULL};
793 field->data = data;
794 field->attr &= ~size_t(signable_e);
795 }
796 return true;
797 default:
798 break;
799 }
800 return false; // type unchanged
801 }
802
803 assert(candidate == FldDisplay || is_elementary(candidate));
804 assert(field->type != FldDisplay); // can never be
805 assert(field->usage == FldInvalid ||
806 field->usage == FldDisplay || is_elementary(field->usage));
807
808 if( ! (field->type == FldInvalid ||
809 field->type == FldGroup || is_elementary(field->type)) ) {
810 return false; // semantic user error
811 }
812
813 // type matches itself
814 if( field->type == candidate ) {
815 if( is_usage ) field->usage = candidate;
816 return true;
817 }
818 if( is_usage && field->usage == candidate ) return true;
819
820 if( ! plausible_usage(field->usage, candidate) ) return false;
821
822 /*
823 * FldDisplay candidate
824 */
825 if( candidate == FldDisplay ) { // update usage at most
826 if( field->type == FldInvalid ||
827 field->type == FldGroup ||
828 is_displayable(field->type) ) {
829 field->usage = candidate;
830 return true;
831 }
832 return false;
833 }
834
835 assert(field->type != candidate && is_elementary(candidate));
836
837 /*
838 * Concrete usage candidate. Update usage first (if USAGE clause), then type.
839 */
840 if( is_usage ) {
841 switch(field->type) {
842 case FldBlob:
843 case FldDisplay:
844 gcc_unreachable(); // type is never just "display"
845 break;
846 case FldAlphaEdited:
847 break;
848 case FldNumericEdited:
849 case FldPointer:
850 if( is_numeric(candidate) ) {
851 return false;
852 }
853 __attribute__((fallthrough));
854 case FldInvalid:
855 case FldGroup:
856 case FldNumericDisplay:
857 field->usage = candidate;
858 break;
859 case FldLiteralA:
860 case FldLiteralN:
861 case FldClass:
862 case FldConditional:
863 case FldForward:
864 case FldIndex:
865 case FldSwitch:
866 gcc_unreachable();
867 case FldAlphanumeric:
868 // MF allows PIC X(n) to have USAGE COMP-[5x]
869 if( candidate != FldNumericBin5 ) return false;
870 if( ! (dialect_mf() && field->has_attr(all_x_e)) ) {
871 return false;
872 }
873 __attribute__((fallthrough));
874 case FldFloat:
875 case FldNumericBin5:
876 case FldNumericBinary:
877 case FldPacked:
878 assert(field->type != candidate); // ensured by test at start of function
879 field->usage = candidate;
880 }
881 }
882
883 // Now, apply (possibly new) usage to type
884 assert( !is_usage || field->usage == candidate );
885
886 /*
887 * Concrete type candidate
888 */
889 switch(field->usage) {
890 case FldInvalid:
891 field->type = candidate;
892 field->attr |= numeric_group_attrs(field);
893 return true;
894 case FldDisplay:
895 if( is_displayable(candidate) ) {
896 field->type = candidate;
897 field->attr |= numeric_group_attrs(field);
898 return true;
899 }
900 break;
901 case FldAlphaEdited:
902 case FldAlphanumeric:
903 assert( dialect_mf() && field->has_attr(all_x_e) );
904 // convert all X's alphanumeric to numeric
905 field->clear_attr(all_x_e);
906 field->type = field->usage;
907 field->attr |= numeric_group_attrs(field);
908 return true;
909 case FldNumericDisplay:
910 case FldNumericEdited:
911 case FldGroup:
912 case FldLiteralA:
913 case FldLiteralN:
914 case FldClass:
915 case FldConditional:
916 case FldForward:
917 case FldSwitch:
918 case FldPointer:
919 case FldBlob:
920 // invalid usage value
921 gcc_unreachable();
922 break;
923 case FldIndex:
924 if( field->usage == candidate ) {
925 field->type = candidate;
926 return true;
927 }
928 break;
929 case FldFloat:
930 case FldNumericBin5:
931 case FldNumericBinary:
932 case FldPacked:
933 if( field->usage == candidate ) {
934 field->type = candidate;
935 return true;
936 }
937 if( candidate == FldNumericDisplay ) {
938 field->type = field->usage;
939 field->attr |= numeric_group_attrs(field);
940 return true;
941 }
942 break;
943 }
944 return false;
945 }
946
947 bool
948 redefine_field( cbl_field_t *field ) {
949 const cbl_field_t *primary = symbol_redefines(field);
950 bool fOK = true;
951
952 if( !primary ) return false;
953
954 if( field->type == FldInvalid ) { // no PICTURE
955 field->type = primary->type;
956 field->data = primary->data;
957 field->data.initial = NULL;
958 }
959
960 if( field->data.capacity == 0 ) field->data = primary->data;
961
962 if( is_numeric(field->type) && field->usage == FldDisplay ) {
963 fOK = symbol_field_type_update(field, FldNumericDisplay, false);
964 }
965
966 return fOK;
967 }
968
969 void
970 cbl_field_t::report_invalid_initial_value(const YYLTYPE& loc) const {
971
972 if( ! data.initial ) return;
973
974 auto fig = cbl_figconst_of(data.initial);
975
976 // numeric initial value
977 if( is_numeric(type) ) {
978 if( has_attr(quoted_e) ) {
979 error_msg(loc, "numeric type %s VALUE '%s' requires numeric VALUE",
980 name, data.initial);
981 return;
982 }
983 if( ! (fig == normal_value_e || fig == zero_value_e) ) {
984 error_msg(loc, "numeric type %s VALUE '%s' requires numeric VALUE",
985 name, cbl_figconst_str(fig));
986 return;
987 }
988
989 switch( type ) {
990 case FldIndex:
991 case FldNumericBin5:
992 if( data.digits == 0 ) {
993 // We are dealing with a pure binary type. If the capacity is
994 // 8 or more, we need do no further testing because we assume
995 // everything fits.
996 if( data.capacity < 8 ) {
997 const char *p = strchr(data.initial, symbol_decimal_point());
998 if( p && atoll(p+1) != 0 ) {
999 error_msg(loc, "integer type %s VALUE '%s' "
1000 "requires integer VALUE",
1001 name, data.initial);
1002 } else {
1003 // Calculate the maximum possible value that a binary with this
1004 // many bytes can hold
1005 size_t max_possible_value;
1006 max_possible_value = 1;
1007 max_possible_value <<= data.capacity*8;
1008 max_possible_value -= 1;
1009 if( attr & signable_e )
1010 {
1011 // Because it is signable, we divide by two to account for the
1012 // sign bit:
1013 max_possible_value >>= 1;
1014 }
1015 // Pick up the given VALUE
1016 size_t candidate;
1017 if( *data.initial == '-' ) {
1018 // We care about the magnitude, not the sign
1019 if( !(attr & signable_e) ){
1020 error_msg(loc, "integer type %s VALUE '%s' "
1021 "requires a non-negative integer",
1022 name, data.initial);
1023 }
1024 candidate = atoll(data.initial+1);
1025 }
1026 else {
1027 candidate = (size_t)atoll(data.initial);
1028 }
1029 if( candidate > max_possible_value ) {
1030 error_msg(loc, "integer type %s VALUE '%s' "
1031 "requires an integer of magnitude no greater than %zu",
1032 name, data.initial, max_possible_value);
1033 }
1034 }
1035 }
1036 }
1037 break;
1038 case FldFloat:
1039 break;
1040 default:
1041 if( ! has_attr(scaled_e) ) {
1042 /*
1043 * Check fraction for excess precision
1044 */
1045 const char *p = strchr(data.initial, symbol_decimal_point());
1046 if( p ) {
1047 auto pend = std::find(p, p + strlen(p), 0x20);
1048 int n = std::count_if( ++p, pend, isdigit );
1049
1050 if( data.precision() < n) {
1051 if( 0 == data.rdigits ) {
1052 error_msg(loc, "integer type %s VALUE '%s' requires integer VALUE",
1053 name, data.initial);
1054 } else {
1055 auto has_exponent = std::any_of( p, pend,
1056 []( char ch ) {
1057 return TOUPPER(ch) == 'E';
1058 } );
1059 if( !has_exponent && data.precision() < pend - p ) {
1060 error_msg(loc, "%s cannot represent VALUE %qs exactly (max %c%ld)",
1061 name, data.initial, '.', (long)(pend - p));
1062 }
1063 }
1064 }
1065 } else {
1066 p = data.initial + strlen(data.initial);
1067 }
1068
1069 /*
1070 * Check magnitude, whether or not there's a decimal point.
1071 */
1072 // skip leading zeros
1073 auto first_digit = std::find_if( data.initial, p,
1074 []( char ch ) {
1075 return ch != '0'; } );
1076 // count remaining digits, up to the decimal point
1077 auto n = std::count_if( first_digit, p, isdigit );
1078 if( data.ldigits() < n ) {
1079 error_msg(loc, "numeric %s VALUE '%s' holds only %u digits",
1080 name, data.initial,
1081 data.digits);
1082 }
1083 }
1084 break;
1085 } // end type switch for normal string initial value
1086 return;
1087 } // end numeric
1088 assert( ! is_numeric(type) );
1089
1090 // consider all-alphabetic
1091 if( has_attr(all_alpha_e) ) {
1092 bool alpha_value = fig != zero_value_e;
1093
1094 if( fig == normal_value_e ) {
1095 alpha_value = std::all_of( data.initial,
1096 data.initial +
1097 strlen(data.initial),
1098 []( char ch ) {
1099 return ISSPACE(ch) ||
1100 ISPUNCT(ch) ||
1101 ISALPHA(ch); } );
1102 }
1103 if( ! alpha_value ) {
1104 error_msg(loc, "alpha-only %s VALUE '%s' contains non-alphabetic data",
1105 name, fig == zero_value_e? cbl_figconst_str(fig) : data.initial);
1106 }
1107 }
1108
1109 return;
1110 }
1111
1112 // Return the field representing the subscript whose literal value
1113 // exceeds the OCCURS clause for that dimension, else NULL if all
1114 // literals are in bounds.
1115 const cbl_field_t *
1116 literal_subscript_oob( const cbl_refer_t& r, size_t& isub /* output */) {
1117 // Verify literal subscripts if dimensions are correct.
1118 size_t ndim(dimensions(r.field));
1119 if( ndim == 0 || ndim != r.nsubscript() ) return NULL;
1120 std::vector<cbl_field_t *> dims( ndim, NULL );
1121 auto pdim = dims.end();
1122
1123 for( auto f = r.field; f; f = parent_of(f) ) {
1124 if( f->occurs.ntimes() ) {
1125 --pdim;
1126 *pdim = f;
1127 }
1128 }
1129 assert(dims[0] != NULL);
1130 assert(pdim == dims.begin());
1131
1132 /*
1133 * For each subscript, if it is a literal, verify it is in bounds
1134 * for the corresponding dimension. Return the first subscript not
1135 * meeting those criteria, if any.
1136 */
1137 auto psub = std::find_if( r.subscripts.begin(), r.subscripts.end(),
1138 [pdim]( const cbl_refer_t& r ) mutable {
1139 const auto& occurs((*pdim)->occurs);
1140 pdim++;
1141 return ! occurs.subscript_ok(r.field);
1142 } );
1143 isub = psub - r.subscripts.begin();
1144 return psub == r.subscripts.end()? NULL : dims[isub];
1145 }
1146
1147 size_t
1148 cbl_refer_t::subscripts_set( const std::list<cbl_refer_t>& subs ) {
1149 subscripts.clear();
1150 std::copy( subs.begin(), subs.end(), std::back_inserter(subscripts) );
1151 return dimensions(field);
1152 }
1153
1154 const char *
1155 cbl_refer_t::str() const {
1156 static char subscripts_l[64];
1157 sprintf(subscripts_l, "(%u of " HOST_SIZE_T_PRINT_UNSIGNED " dimensions)",
1158 nsubscript(), (fmt_size_t)dimensions(field));
1159 char *output = xasprintf("%s %s %s",
1160 field? field_str(field) : "(none)",
1161 0 < dimensions(field)? subscripts_l : "",
1162 is_refmod_reference()? "(refmod)" : "" );
1163 return output;
1164 }
1165 const char *
1166 cbl_refer_t::name() const {
1167 if( prog_func ) return prog_func->name;
1168 char *output = xasprintf("%s", field? field->name : "(none)" );
1169 return output;
1170 }
1171
1172 const char *
1173 cbl_refer_t::deref_str() const {
1174 std::vector<char> dimstr(nsubscript() * 16, '\0');
1175 dimstr.at(0) = '(';
1176 auto p = dimstr.begin() + 1;
1177
1178 if( !field ) return name();
1179
1180 for( const auto& sub : subscripts ) {
1181 auto initial = sub.field->data.initial ? sub.field->data.initial : "?";
1182 size_t len = dimstr.end() - p;
1183 p += snprintf( &*p, len, "%s ", initial );
1184 }
1185 if( ! subscripts.empty() ) {
1186 *--p = ')';
1187 }
1188 char *output = xasprintf("%s%s", field->name, dimstr.data());
1189 return output;
1190 }
1191
1192 struct move_corresponding_field {
1193 cbl_refer_t tgt, src;
1194
1195 move_corresponding_field( const cbl_refer_t& tgt, const cbl_refer_t& src )
1196 : tgt(tgt), src(src) {}
1197
1198 void operator()( corresponding_fields_t::const_reference elem ) {
1199 if( elem.second == 0 ) return;
1200 src.field = cbl_field_of(symbol_at(elem.first));
1201 tgt.field = cbl_field_of(symbol_at(elem.second));
1202
1203 if( yydebug ) {
1204 dbgmsg("move_corresponding:%d: SRC: %3" GCC_PRISZ "u %s", __LINE__,
1205 (fmt_size_t)elem.first, src.str());
1206 dbgmsg("move_corresponding:%d: to %3" GCC_PRISZ "u %s", __LINE__,
1207 (fmt_size_t)elem.second, tgt.str());
1208 }
1209
1210 parser_move(tgt, src);
1211 }
1212 };
1213
1214 bool
1215 move_corresponding( cbl_refer_t& tgt, cbl_refer_t& src )
1216 {
1217 assert(tgt.field && src.field);
1218 assert(tgt.field->type == FldGroup);
1219 assert(src.field->type == FldGroup);
1220
1221 corresponding_fields_t pairs = corresponding_move_fields( src.field,
1222 tgt.field );
1223 if( pairs.empty() ) return false;
1224
1225 std::for_each( pairs.begin(), pairs.end(),
1226 move_corresponding_field(tgt, src) );
1227 return true;
1228 }
1229
1230 bool
1231 valid_move( const struct cbl_field_t *tgt, const struct cbl_field_t *src )
1232 {
1233 // This is the base matrix of allowable moves. Moves from Alphanumeric are
1234 // modified based on the attribute bit all_alpha_e, and moves from Numeric
1235 // types to Alphanumeric and AlphanumericEdited are allowable when the
1236 // Numeric type is integer, and not allowed when the type has digits to the
1237 // right of the decimal point.
1238
1239 // Note that the ordering of elements in this matrix has to match the
1240 // ordering of the symbols.h elements in enum cbl_field_type_t.
1241
1242 static const unsigned char matrix[FldLiteralN+1][FldLiteralN+1] = {
1243 // src down, tgt across
1244 //I G A B F P 5 ND NE AE LA LN
1245 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // FldInvalid
1246 { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, }, // FldGroup
1247 { 0, 1, 1, 8, 8, 8, 8, 8, 8, 1, 0, 0, }, // FldAlphanumeric
1248 { 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericBinary (numeric)
1249 { 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, }, // FldFloat
1250 { 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldPacked (numeric)
1251 { 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericBin5 (numeric)
1252 { 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericDisplay (numeric)
1253 { 0, 1, 4, 1, 1, 1, 1, 1, 1, 1, 0, 0, }, // FldNumericEdited
1254 { 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // FldAlphaEdited
1255 { 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // FldLiteralA
1256 { 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldLiteralN (numeric)
1257 };
1258 /* Needs C++11 */
1259 static_assert(sizeof(matrix[0]) == COUNT_OF(matrix[0]),
1260 "matrix should be square");
1261
1262 for( auto field : { src, tgt } ) {
1263 switch(field->type) {
1264 case FldClass:
1265 case FldConditional:
1266 case FldIndex:
1267 case FldSwitch:
1268 case FldDisplay:
1269 case FldPointer:
1270 return false;
1271 // parser should not allow the following types here
1272 case FldForward:
1273 case FldBlob:
1274 default:
1275 if( sizeof(matrix[0]) < field->type ) {
1276 cbl_internal_error("logic error: MOVE %s %s invalid type:",
1277 cbl_field_type_str(field->type), field->name);
1278 }
1279 break;
1280 }
1281 }
1282
1283 assert(tgt->type < sizeof(matrix[0]));
1284 assert(src->type < sizeof(matrix[0]));
1285
1286 // A value of zero means the move is prohibited.
1287 // The 1 bit means the move is allowed
1288 // The 2 bit means the move is allowed if the source has zero rdigits,
1289 // or is P-scaled
1290 // The 4 bit means the move is allowed if dest all_alpha_e is off.
1291 // The 8 bit means the move is allowed if source all_alpha_e is off.
1292
1293 bool retval = false;
1294 bool nofraction = src->data.rdigits == 0 || src->has_attr(scaled_e);
1295 bool alphabetic = tgt->has_attr(all_alpha_e);
1296 bool src_alpha = src->has_attr(all_alpha_e);
1297
1298 switch( matrix[src->type][tgt->type] )
1299 {
1300 case 0:
1301 if( src->type == FldLiteralA && is_numericish(tgt) && !is_literal(tgt) ) {
1302 // Allow if input string is an integer.
1303 const char *p = src->data.initial, *pend = p + src->data.capacity;
1304 if( p[0] == '+' || p[0] == '-' ) p++;
1305 retval = std::all_of( p, pend, isdigit );
1306 if( yydebug && ! retval ) {
1307 auto bad = std::find_if( p, pend,
1308 []( char ch ) { return ! ISDIGIT(ch); } );
1309 dbgmsg("%s:%d: offending character '%c' at position "
1310 HOST_SIZE_T_PRINT_UNSIGNED,
1311 __func__, __LINE__, *bad, (fmt_size_t)(bad - p));
1312 }
1313 }
1314 break;
1315 case 1:
1316 retval = true;
1317 break;
1318 case 2:
1319 retval = nofraction;
1320 break;
1321 case 4:
1322 retval = !alphabetic;
1323 break;
1324 case 6:
1325 retval = nofraction && !alphabetic;
1326 break;
1327 case 8:
1328 retval = !src_alpha;
1329 break;
1330 default:
1331 dbgmsg("%s:%d: matrix at %s, %s is %d", __func__, __LINE__,
1332 cbl_field_type_str(src->type), cbl_field_type_str(tgt->type),
1333 matrix[src->type][tgt->type]);
1334 gcc_unreachable();
1335 }
1336
1337 if( retval && src->has_attr(embiggened_e) ) {
1338 if( is_numeric(tgt) && tgt->data.capacity < src->data.capacity ) {
1339 dbgmsg("error: source no longer fits in target");
1340 return false;
1341 }
1342 }
1343
1344 return retval;
1345 }
1346
1347 bool
1348 valid_picture( enum cbl_field_type_t type, const char picture[] )
1349 {
1350 switch(type) {
1351 case FldBlob:
1352 gcc_unreachable(); // can't get here via the parser
1353 case FldInvalid:
1354 case FldGroup:
1355 case FldLiteralA:
1356 case FldLiteralN:
1357 case FldClass:
1358 case FldConditional:
1359 case FldForward:
1360 case FldIndex:
1361 case FldSwitch:
1362 case FldDisplay:
1363 case FldPointer:
1364 // These types don't take pictures; the grammar shouldn't call the function.
1365 dbgmsg("%s:%d: no polaroid: %s", __func__, __LINE__, cbl_field_type_str(type));
1366 return false;
1367 case FldNumericBinary:
1368 case FldFloat:
1369 case FldNumericBin5:
1370 case FldPacked:
1371 // Validated in scan.l.
1372 return true;
1373 case FldAlphanumeric:
1374 // Cannot be all As or all 9s.
1375 return !( memall(picture, 'A') || memall(picture, '9') );
1376 case FldNumericDisplay:
1377 // Must have A or X and B, 0, or /.
1378 return match(picture, "[AX]") && match(picture, "[B0/]");
1379 case FldNumericEdited:
1380 case FldAlphaEdited:
1381 break;
1382 }
1383 assert(type == FldNumericEdited );
1384
1385 // Must contain at least one 0, B, /, Z, *, +, (comma), ., –, CR, DB, or cs.
1386 if( ! match( picture, "[$0B/Z*+.,+–]|DB$|CR$" ) ) {
1387 return false;
1388 }
1389
1390 return true;
1391 }
1392
1393 uint32_t
1394 type_capacity( enum cbl_field_type_t type, uint32_t digits )
1395 {
1396 switch(type) {
1397 case FldBlob: gcc_unreachable();
1398 case FldInvalid:
1399 case FldGroup:
1400 case FldAlphanumeric:
1401 case FldNumericDisplay:
1402 case FldNumericEdited:
1403 case FldAlphaEdited:
1404 case FldClass:
1405 case FldConditional:
1406 case FldForward:
1407 case FldIndex:
1408 case FldSwitch:
1409 case FldDisplay:
1410 case FldPointer:
1411 return digits;
1412 case FldFloat:
1413 case FldNumericBinary:
1414 case FldNumericBin5:
1415 case FldLiteralA:
1416 case FldLiteralN:
1417 break;
1418 case FldPacked:
1419 return (digits+2)/2; // one nybble per digit + a sign nybble
1420 }
1421
1422 static const struct sizes_t {
1423 std::pair<uint32_t, uint32_t> bounds;
1424 size_t size;
1425 sizes_t( uint32_t first, uint32_t last, uint32_t size )
1426 : bounds(first, last), size(size)
1427 {}
1428 } sizes[] = {
1429 { 1, 4, 2 },
1430 { 5, 9, 4 },
1431 {10, 18, 8 },
1432 {19, 38, 16 },
1433 }, *esizes = sizes + COUNT_OF(sizes);
1434
1435 auto psize = std::find_if( sizes, esizes,
1436 [digits]( sizes_t sizes ) {
1437 return sizes.bounds.first <= digits && digits <= sizes.bounds.second;
1438 } );
1439 if( psize != esizes ) return psize->size;
1440
1441 dbgmsg( "%s:%d: invalid size %u for type %s", __func__, __LINE__,
1442 digits, cbl_field_type_str(type) );
1443
1444 return digits;
1445 }
1446
1447 typedef char hex_pair_t[2];
1448
1449 class scan_hex {
1450 public:
1451 unsigned char operator()( const hex_pair_t input ) {
1452 static char buffer[ sizeof(hex_pair_t) + 1 ] = "";
1453
1454 memcpy( buffer, input, sizeof(buffer) - 1 );
1455 unsigned int x;
1456 sscanf( buffer, "%x", &x );
1457 return x;
1458 }
1459 };
1460
1461 /*
1462 * Convert hexadecimal string to ASCII, e.g. X'434154' to "CAT".
1463 */
1464 char *
1465 hex_decode( const char input[] ) {
1466 const size_t len = strlen(input);
1467 assert( 0 == len % 2 );
1468
1469 auto output = static_cast<char *>(xcalloc( 1, 1 + len / 2 ));
1470 auto beg = reinterpret_cast<const hex_pair_t*>(input + 0),
1471 end = reinterpret_cast<const hex_pair_t*>(input + len);
1472 std::transform( beg, end, output, scan_hex() );
1473 return output;
1474 }
1475
1476 /*
1477 * Verify unique procedure reference.
1478 *
1479 * Section and paragraph names need not be unique unless they are
1480 * referenced, for example by PERFORM.
1481 *
1482 * When a program contains sections, a paragraph can be referenced
1483 * without qualification if it's unique within the current section or
1484 * globally. Else <para> OF <sect> is required. That means the
1485 * validity of a reference depends on location of reference, which is
1486 * why order matters. (We can't use line number because the Cobol text
1487 * could be all on one line.)
1488 *
1489 * We maintain a map of referenceable {section,paragraph} pairs, with
1490 * a count. A count of 1 means it's globally unique.
1491 *
1492 * For local calls, we maintain a multimap of sections (whose names might
1493 * not be unique) in order of appearance. For each section, we have a
1494 * set of paragraph names defined by the section, and a count, plus a
1495 * list of references: {section,paragraph} names used by PERFORM or
1496 * similar.
1497 *
1498 * To determine if a call is valid:
1499 * For each key {section}:
1500 * for each reference:
1501 * Local: if section is empty or matches the key, the call is valid if
1502 * if the paragraph name is unique within section:
1503 * valid if count == 1
1504 * Global: valid if {section,paragraph} is unique in the global map
1505 *
1506 * Line numbers are just decoration.
1507 */
1508
1509 bool
1510 procref_base_t::operator<( const procref_base_t& that ) const {
1511 int result = strcasecmp(section(), that.section());
1512
1513 if( result == 0 ) {
1514 return strcasecmp(paragraph(), that.paragraph()) < 0;
1515 }
1516 return result < 0;
1517 }
1518
1519 bool
1520 procref_base_t::operator==( const procref_base_t& that ) const {
1521 return
1522 0 == strcasecmp(section(), that.section()) &&
1523 0 == strcasecmp(paragraph(), that.paragraph());
1524 }
1525
1526 class procdef_t : public procref_base_t {
1527 size_t isym;
1528 public:
1529 procdef_t( const char *section, const char *paragraph, size_t isym )
1530 : procref_base_t(section, paragraph)
1531 , isym(isym)
1532 {
1533 assert(isym);
1534 }
1535 explicit procdef_t( const procref_base_t& ref )
1536 : procref_base_t(ref)
1537 , isym(0)
1538 {}
1539
1540 bool operator<( const procdef_t& that ) const {
1541 return procref_base_t(*this) < procref_base_t(that);
1542 }
1543
1544 cbl_label_t * label_of() const {
1545 return isym == 0? NULL : cbl_label_of(symbol_at(isym));
1546 }
1547 };
1548
1549 /*
1550 * Every reference occurs in a {program,section,paragraph} context,
1551 * even if they're implicit.
1552 */
1553
1554 typedef std::multimap<procdef_t, std::list<procref_t>> procedures_t;
1555
1556 static std::map<size_t, procedures_t> programs;
1557 static procedures_t::iterator current_procedure = programs.end()->second.end();
1558
1559 /*
1560 * If a procedure reference uses only one name, it could refer to a
1561 * section or paragraph. The "paragraph" name in the reference, if not
1562 * paired with a section name, might refer to a section.
1563 *
1564 * For a 1-name reference:
1565 * a global match means the name is defined exactly once
1566 * a local match matches a unique paragraph name in the
1567 * section in which the reference occurs, or the section name itself
1568 *
1569 * No paragraph can have the same name as a section.
1570 */
1571 class procedure_match {
1572 const procref_base_t& ref;
1573 public:
1574 explicit procedure_match( const procref_base_t& ref ) : ref(ref) {}
1575 // Match a 2-name reference to section & paragraph, else to one or the other.
1576 bool operator()( procedures_t::const_reference elem ) {
1577 const procdef_t& key = elem.first;
1578
1579 if( ref.has_section() ) return ref == key;
1580
1581 bool hit =
1582 (!key.has_paragraph() && 0 == strcasecmp(key.section(), ref.paragraph()))
1583 || 0 == strcasecmp(key.paragraph(), ref.paragraph());
1584 return hit;
1585 }
1586 };
1587
1588 static bool
1589 globally_unique( size_t program, const procref_t& ref ) {
1590 const procedures_t& procedures = programs[program];
1591 assert(!procedures.empty());
1592 return 1 == count_if(procedures.begin(), procedures.end(), procedure_match(ref));
1593 }
1594
1595 static bool
1596 locally_unique( size_t program, const procdef_t& key, const procref_t& ref ) {
1597 const procedures_t& procedures = programs[program];
1598 assert(!procedures.empty());
1599 const char *section_name = ref.has_section()? ref.section() : key.section();
1600 procref_base_t full_ref(section_name, ref.paragraph());
1601
1602 return 1 == procedures.count(procdef_t(full_ref));
1603 }
1604
1605 // Add each section and paragraph to the map as it occurs in the Cobol text.
1606 void
1607 procedure_definition_add( size_t program, const cbl_label_t *procedure ) {
1608 const char *section_name = NULL, *paragraph_name = NULL;
1609 size_t isym = symbol_index(symbol_elem_of(procedure));
1610
1611 if( procedure->type == LblParagraph ) {
1612 if( procedure->parent > 0) {
1613 section_name = cbl_label_of(symbol_at(procedure->parent))->name;
1614 }
1615 paragraph_name = procedure->name;
1616
1617 } else {
1618 assert( procedure->type == LblSection );
1619 section_name = procedure->name;
1620 }
1621
1622 procdef_t key( section_name, paragraph_name, isym );
1623 current_procedure =
1624 programs[program].insert( make_pair(key, procedures_t::mapped_type()) );
1625 }
1626
1627 // Add each procedure reference as it occurs in the Cobol text, in context.
1628 void
1629 procedure_reference_add( const char *section, const char *paragraph,
1630 int line, size_t context )
1631 {
1632 current_procedure->second.push_back( procref_t(section, paragraph,
1633 line, context) );
1634 }
1635
1636 // Verify each reference in a map element is locally or globally unique
1637 class is_unique {
1638 size_t program;
1639 procedures_t::key_type key;
1640 public:
1641 is_unique( size_t program, const procedures_t::key_type& key )
1642 : program(program)
1643 , key(key)
1644 {}
1645
1646 bool operator()( procedures_t::mapped_type::const_reference ref ) {
1647 return
1648 locally_unique( program, key, ref ) ||
1649 globally_unique( program, ref);
1650 }
1651 };
1652
1653 procref_t *
1654 ambiguous_reference( size_t program ) {
1655 procedures_t& procedures = programs[program];
1656
1657 for( const auto& proc : procedures ) {
1658 procedures_t::mapped_type::const_iterator
1659 ambiguous = find_if_not( proc.second.begin(), proc.second.end(),
1660 is_unique(program, proc.first) );
1661 if( proc.second.end() != ambiguous ) {
1662 if( yydebug ) {
1663 dbgmsg("%s: %s of '%s' has " HOST_SIZE_T_PRINT_UNSIGNED
1664 "potential matches", __func__,
1665 ambiguous->paragraph(), ambiguous->section(),
1666 (fmt_size_t)procedures.count(procdef_t(*ambiguous)));
1667 }
1668 return new procref_t(*ambiguous);
1669 }
1670 }
1671 return NULL;
1672 }
1673
1674 /*
1675 * See declaratives nonterminal in parse.y
1676 */
1677 // Todo: unused
1678 cbl_label_t *
1679 intradeclarative_reference() {
1680 const procedures_t& procedures = programs[current_program_index()];
1681
1682 for( auto elem : procedures ) {
1683 procdef_t key( elem.first );
1684 auto L = key.label_of();
1685 if( L->type != LblNone ) return L;
1686 }
1687 return NULL;
1688 }
1689
1690 class next_group {
1691 size_t isym;
1692 public:
1693 explicit next_group( const symbol_elem_t *group ) : isym(symbol_index(group)) {}
1694
1695 // return true if elem is not a member of the group
1696 bool operator()( const symbol_elem_t& elem ) {
1697 if( elem.type != SymField ) return false;
1698 if( symbol_index(&elem) == isym ) return false;
1699 return cbl_field_of(&elem)->parent < isym;
1700 }
1701 };
1702
1703 static void
1704 parent_names( const symbol_elem_t *elem,
1705 const symbol_elem_t *group, std::list<const char *>& names ) {
1706
1707 if( is_filler(cbl_field_of(elem)) ) return;
1708
1709 // dbgmsg("%s: asked about %s of %s (" HOST_SIZE_T_PRINT_UNSIGNED " away)", __func__,
1710 // cbl_field_of(elem)->name,
1711 // cbl_field_of(group)->name, (fmt_size_t)(elem - group));
1712
1713 for( const symbol_elem_t *e=elem; e && group < e; e = symbol_parent(e) ) {
1714 names.push_front( cbl_field_of(e)->name );
1715 }
1716 }
1717
1718 extern int yylineno;
1719 class find_corresponding {
1720 public:
1721 enum type_t { arith_op, move_op };
1722 private:
1723 symbol_elem_t *lgroup, *rgroup;
1724 type_t type;
1725 public:
1726 find_corresponding( symbol_elem_t *lgroup,
1727 symbol_elem_t *rgroup, type_t type )
1728 : lgroup(lgroup), rgroup(rgroup), type(type)
1729 {
1730 dbgmsg( "%s:%d: for #" HOST_SIZE_T_PRINT_UNSIGNED
1731 " %s and #" HOST_SIZE_T_PRINT_UNSIGNED " %s on line %d",
1732 __func__, __LINE__,
1733 (fmt_size_t)symbol_index(lgroup), cbl_field_of(lgroup)->name,
1734 (fmt_size_t)symbol_index(rgroup), cbl_field_of(rgroup)->name, yylineno );
1735 }
1736
1737 static bool
1738 any_redefines( const cbl_field_t& field, const symbol_elem_t *group ) {
1739 for( const cbl_field_t *f = &field; f && f->parent > 0; f = parent_of(f) ) {
1740 const symbol_elem_t *e = symbol_at(f->parent);
1741 if( e == group || e->type != SymField ) break;
1742 if( symbol_redefines(f) ) return true;
1743 }
1744 return false;
1745 }
1746
1747 corresponding_fields_t::value_type
1748 operator()( const symbol_elem_t& that ) {
1749 if( &that == lgroup ) return std::make_pair(0,0);
1750 if( that.type != SymField ) return std::make_pair(0,0);
1751
1752 const cbl_field_t& lfield( *cbl_field_of(&that) );
1753
1754 switch(lfield.level) {
1755 case 66: case 77: case 88:
1756 return std::make_pair(0,0);
1757 default:
1758 if( any_redefines(lfield, lgroup) ) return std::make_pair(0,0);
1759 if( is_filler(&lfield) ) return std::make_pair(0,0);
1760 if( is_table(&lfield) ) return std::make_pair(0,0);
1761 break;
1762 }
1763
1764 std::list<const char *> names;
1765 parent_names( &that, lgroup, names );
1766 names.push_front(cbl_field_of(rgroup)->name);
1767
1768 symbol_elem_t *e = symbol_find_of( that.program, names, symbol_index(rgroup) );
1769 if( !e ) return std::make_pair(0,0);
1770
1771 const cbl_field_t& rfield( *cbl_field_of(e) );
1772
1773 switch(rfield.level) {
1774 case 66: case 77: case 88:
1775 return std::make_pair(0,0);
1776 default:
1777 if( any_redefines(rfield, rgroup) ) return std::make_pair(0,0);
1778 if( is_table(&rfield) ) return std::make_pair(0,0);
1779 break;
1780 }
1781
1782 switch(type) {
1783 case arith_op:
1784 if( !(is_numeric(lfield.type) && is_numeric(rfield.type)) ) {
1785 return std::make_pair(0,0);
1786 }
1787 break;
1788 case move_op:
1789 if( !(is_elementary(lfield.type) || is_elementary(rfield.type)) ) {
1790 return std::make_pair(0,0);
1791 }
1792 break;
1793 }
1794
1795 return std::make_pair( symbol_index(&that), symbol_index(e));
1796 }
1797 };
1798
1799 static corresponding_fields_t
1800 corresponding_fields( cbl_field_t *lhs, cbl_field_t *rhs,
1801 find_corresponding::type_t type ) {
1802 corresponding_fields_t output;
1803 assert(lhs); assert(rhs);
1804 assert(lhs->type == FldGroup && rhs->type == FldGroup);
1805
1806 struct { symbol_elem_t *a, *z; } lhsg;
1807
1808 lhsg.a = symbols_begin(field_index(lhs));
1809 lhsg.z = std::find_if( lhsg.a, symbols_end(), next_group(lhsg.a) );
1810
1811 dbgmsg("%s:%d: examining " HOST_SIZE_T_PRINT_UNSIGNED " symbols after %s",
1812 __func__, __LINE__,
1813 (fmt_size_t)(lhsg.z - lhsg.a), lhs->name);
1814
1815 find_corresponding finder( symbol_at(field_index(lhs)),
1816 symbol_at(field_index(rhs)), type );
1817 std::transform( lhsg.a, lhsg.z, std::inserter(output, output.begin()), finder );
1818
1819 output.erase(0);
1820
1821 dbgmsg( "%s:%d: %s and %s have " HOST_SIZE_T_PRINT_UNSIGNED
1822 " corresponding fields",
1823 __func__, __LINE__, lhs->name, rhs->name, (fmt_size_t)output.size() );
1824
1825 return output;
1826 }
1827
1828 corresponding_fields_t
1829 corresponding_move_fields( cbl_field_t *lhs, cbl_field_t *rhs ) {
1830 return corresponding_fields( lhs, rhs, find_corresponding::move_op );
1831 }
1832
1833 corresponding_fields_t
1834 corresponding_arith_fields( cbl_field_t *lhs, cbl_field_t *rhs ) {
1835 return corresponding_fields( lhs, rhs, find_corresponding::arith_op );
1836 }
1837
1838 char
1839 date_time_fmt( const char input[] ) {
1840 if( ! input ) return 0;
1841
1842 #define DATE_FMT_B "(YYYYMMDD|YYYYDDD|YYYYWwwD)"
1843 #define DATE_FMT_E "(YYYY-MM-DD|YYYY-DDD|YYYY-Www-D)"
1844 #define TIME_FMT1 "hhmmss([.,]s+)?"
1845 #define TIME_FMT3 "hhmmss([.,]s+)?Z"
1846 #define TIME_FMT5 "hhmmss([.,]s+)?[+]hhmm"
1847 #define TIME_FMT2 "hh:mm:ss([.,]s+)?"
1848 #define TIME_FMT4 "hh:mm:ss([.,]s+)?Z"
1849 #define TIME_FMT6 "hh:mm:ss([.,]s+)?[+]hh:mm"
1850
1851 #define TIME_FMT_B "(" TIME_FMT1 "|" TIME_FMT3 "|" TIME_FMT5 ")"
1852 #define TIME_FMT_E "(" TIME_FMT2 "|" TIME_FMT4 "|" TIME_FMT6 ")"
1853
1854 static bool compiled = false;
1855 static struct fmts_t {
1856 regex_t reg; char type; char pattern[256];
1857 } fmts[] = {
1858 { regex_t(), 'D', "^((" DATE_FMT_B "T" TIME_FMT_B ")|("
1859 DATE_FMT_E "T" TIME_FMT_E "))$" },
1860 { regex_t(), 'd', "^(" DATE_FMT_B "|" DATE_FMT_E ")$" },
1861 { regex_t(), 't', "^(" TIME_FMT_B "|" TIME_FMT_E ")$" },
1862 };
1863 int cflags = REG_EXTENDED | REG_ICASE, eflags=0;
1864 regmatch_t m[5];
1865 char result = 0;
1866
1867 if( ! compiled ) {
1868 for( auto& fmt : fmts ) {
1869 int erc;
1870 if( (erc = regcomp(&fmt.reg, fmt.pattern, cflags)) != 0 ) {
1871 char msg[80];
1872 regerror(erc, &fmt.reg, msg, sizeof(msg));
1873 cbl_errx( "%s: regcomp: %s", __func__, msg );
1874 }
1875 }
1876 compiled = true;
1877 }
1878
1879 for( auto& fmt : fmts ) {
1880 if( 0 == regexec(&fmt.reg, input, COUNT_OF(m), m, eflags) ) {
1881 result = fmt.type;
1882 break;
1883 }
1884 }
1885
1886 return result;
1887 }
1888
1889
1890
1891 /*
1892 * Development suppport
1893 */
1894
1895 #pragma GCC diagnostic push
1896 #pragma GCC diagnostic ignored "-Wunused-variable"
1897
1898 struct input_file_t {
1899 ino_t inode;
1900 int lineno;
1901 const char *name;
1902
1903 input_file_t( const char *name, ino_t inode,
1904 int lineno=1 )
1905 : inode(inode), lineno(lineno), name(name)
1906 {
1907 if( inode == 0 ) inode_set();
1908 }
1909 bool operator==( const input_file_t& that ) const {
1910 return inode == that.inode;
1911 }
1912 protected:
1913 void inode_set() {
1914 struct stat sb;
1915 if( -1 == stat(name, &sb) ) {
1916 cbl_err( "could not stat '%s'", name);
1917 }
1918 inode = sb.st_ino;
1919 }
1920 };
1921
1922 class unique_stack : public std::stack<input_file_t>
1923 {
1924 friend void cobol_set_pp_option(int opt);
1925 bool option_m;
1926 std::set<std::string> all_names;
1927
1928 const char *
1929 no_wd( const char *wd, const char *name ) {
1930 int i;
1931 for( i=0; wd[i] == name[i]; i++ ) i++;
1932 if( wd[i] == '\0' && name[i] == '/' ) i++;
1933 return yydebug? name : name + i;
1934 }
1935
1936 public:
1937 unique_stack() : option_m(false) {}
1938
1939 bool push( const value_type& value ) {
1940 auto ok = std::none_of( c.cbegin(), c.cend(),
1941 [value]( const auto& that ) {
1942 return value == that;
1943 } );
1944 if( ok ) {
1945 std::stack<input_file_t>::push(value);
1946 all_names.insert(value.name);
1947 return true;
1948 }
1949 size_t n = c.size();
1950 if( n > 1 ) {
1951 char *wd = get_current_dir_name();
1952 if( wd ) {
1953 dbgmsg( "depth line copybook filename\n"
1954 "----- ---- --------"
1955 "----------------------------------------");
1956 for( const auto& v : c ) {
1957 dbgmsg( " %4" GCC_PRISZ "u %4d %s",
1958 (fmt_size_t)(c.size() - --n), v.lineno, no_wd(wd, v.name) );
1959 }
1960 } else {
1961 dbgmsg("unable to get current working directory: %s", xstrerror(errno));
1962 }
1963 free(wd);
1964 }
1965 return false;
1966 }
1967
1968 // Look down into the stack. peek(0) == top()
1969 const input_file_t& peek( size_t n ) const {
1970 gcc_assert( n < size() );
1971 return c.at(size() - ++n);
1972 }
1973
1974 void option( int opt ) { // capture other preprocessor options eventually
1975 assert(opt == 'M');
1976 option_m = true;
1977 }
1978 int option() const {
1979 return option_m? 'M' : 0;
1980 }
1981
1982 void print() const {
1983 std::string input( top().name );
1984 printf( "%s: ", input.c_str() );
1985 for( const auto& name : all_names ) {
1986 if( name != input )
1987 printf( "\\\n\t%s ", name.c_str() );
1988 }
1989 printf("\n");
1990 }
1991 };
1992
1993 static const char *input_filename_vestige;
1994 static unique_stack input_filenames;
1995 static std::map<std::string, ino_t> old_filenames;
1996 static const unsigned int sysp = 0; // not a C header file, cf. line-map.h
1997
1998 void cobol_set_pp_option(int opt) {
1999 // capture other preprocessor options eventually
2000 assert(opt == 'M');
2001 input_filenames.option_m = true;
2002 }
2003
2004 /*
2005 * Maintain a stack of input filenames. Ensure the files are unique (by
2006 * inode), to prevent copybook cycles. Before pushing a new name, Record the
2007 * line number that was is current for the current name, so that it can be
2008 * restored when the usurper is popped.
2009 *
2010 * Both the file-reader (lexio) and the scanner use this stack. Lexio uses it
2011 * to enforce uniqueness, and the scanner to maintain line numbers.
2012 */
2013 bool cobol_filename( const char *name, ino_t inode ) {
2014 //const line_map *lines = NULL;
2015 if( inode == 0 ) {
2016 auto p = old_filenames.find(name);
2017 if( p == old_filenames.end() ) {
2018 for( auto& elem : old_filenames ) {
2019 dbgmsg("%6" GCC_PRISZ "u %-30s",
2020 (fmt_size_t)elem.second, elem.first.c_str());
2021 }
2022 cbl_errx( "logic error: missing inode for %s", name);
2023 }
2024 else {
2025 inode = p->second;
2026 assert(inode != 0);
2027 }
2028 }
2029 linemap_add(line_table, LC_ENTER, sysp, name, 1);
2030 input_filename_vestige = name;
2031 bool pushed = input_filenames.push( input_file_t(name, inode, 1) );
2032 return pushed;
2033 }
2034
2035 const char *
2036 cobol_lineno( int lineno ) {
2037 if( input_filenames.empty() ) return NULL;
2038 auto& input( input_filenames.top() );
2039 input.lineno = lineno;
2040 return input.name;
2041 }
2042
2043 /*
2044 * This function is called from the scanner, usually when a copybook is on top
2045 * of the input stack, before the parser retrieves the token and resets the
2046 * current filename. For that reason, we normaly want to line number of the
2047 * file that is about to become the current one, which is the one behind top().
2048 *
2049 * If somehow we arrive here when there is nothing underneath, we return the
2050 * current line nubmer, or zero if there's no input. The only consequence is
2051 * that the reported line number might be wrong.
2052 */
2053 int
2054 cobol_lineno() {
2055 if( input_filenames.empty() ) return 0;
2056 size_t n = input_filenames.size() < 2? 0 : 1;
2057 const auto& input( input_filenames.peek(n) );
2058 return input.lineno;
2059 }
2060
2061 const char *
2062 cobol_filename() {
2063 return input_filenames.empty()? input_filename_vestige : input_filenames.top().name;
2064 }
2065
2066 void
2067 cobol_filename_restore() {
2068 assert(!input_filenames.empty());
2069 const input_file_t& top( input_filenames.top() );
2070 old_filenames[top.name] = top.inode;
2071 input_filename_vestige = top.name;
2072
2073 input_filenames.pop();
2074 if( input_filenames.empty() ) return;
2075
2076 const auto& input = input_filenames.top();
2077
2078 linemap_add(line_table, LC_LEAVE, sysp, NULL, 0);
2079 }
2080
2081 static int first_line_minus_1 = 0;
2082 static location_t token_location_minus_1 = 0;
2083 static location_t token_location = 0;
2084
2085 location_t current_token_location() { return token_location; }
2086 location_t current_location_minus_one() { return token_location_minus_1; }
2087 void current_location_minus_one_clear()
2088 {
2089 first_line_minus_1 = 0;
2090 }
2091
2092 template <typename LOC>
2093 static void
2094 gcc_location_set_impl( const LOC& loc ) {
2095 // Set the position to the first line & column in the location.
2096 if( getenv("KILROY") )
2097 {
2098 fprintf(stderr, "********** KILROY %d\n", loc.first_line);
2099 }
2100
2101 static location_t loc_m_1 = 0;
2102
2103 token_location = linemap_line_start( line_table, loc.first_line, 80 );
2104 token_location = linemap_position_for_column( line_table, loc.first_column);
2105
2106 if( loc.first_line > first_line_minus_1 )
2107 {
2108 // In order for GDB-COBOL to be able to step through COBOL code properly,
2109 // it is sometimes necessary for the code at the beginning of a COBOL
2110 // line to be using the location_t of the previous line. This is true, for
2111 // example, when laying down the infrastructure code between the last
2112 // statement of a paragraph and the code created at the beginning of the
2113 // following paragragh. This code assumes that token_location values of
2114 // interest are monotonic, and stores that prior value.
2115 first_line_minus_1 = loc.first_line;
2116 token_location_minus_1 = loc_m_1;
2117 loc_m_1 = token_location;
2118 }
2119
2120 location_dump(__func__, __LINE__, "parser", loc);
2121 }
2122
2123 void gcc_location_set( const YYLTYPE& loc ) {
2124 gcc_location_set_impl(loc);
2125 }
2126
2127 void gcc_location_set( const YDFLTYPE& loc ) {
2128 gcc_location_set_impl(loc);
2129 }
2130
2131 #ifdef NDEBUG
2132 # define verify_format(M)
2133 #else
2134 #include <regex.h>
2135
2136 static void
2137 verify_format( const char gmsgid[] ) {
2138 static const char pattern[] = "%[[:digit:]][[:digit:].]*[^s]";
2139 static regex_t re;
2140 static int cflags = REG_EXTENDED;
2141 static int status = regcomp( &re, pattern, cflags );
2142
2143 if( status != 0 ) {
2144 static char errbuf[80];
2145 int n = regerror(status, &re, errbuf, sizeof(errbuf));
2146 gcc_assert(size_t(n) < sizeof(errbuf));
2147 fprintf(stderr, "%s:%d: %s", __func__, __LINE__, errbuf);
2148 return;
2149 }
2150 gcc_assert(status == 0);
2151
2152 regmatch_t rm[30];
2153
2154 if( REG_NOMATCH != regexec(&re, gmsgid, COUNT_OF(rm), rm, 0) ){
2155 fprintf(stderr, "bad diagnositic format: '%s'\n", gmsgid);
2156 }
2157 }
2158 #endif
2159
2160 static const diagnostic_option_id option_zero;
2161 size_t parse_error_inc();
2162
2163 void gcc_location_dump() {
2164 linemap_dump_location( line_table, token_location, stderr );
2165 }
2166
2167
2168 void ydferror( const char gmsgid[], ... ) ATTRIBUTE_GCOBOL_DIAG(1, 2);
2169
2170 void
2171 ydferror( const char gmsgid[], ... ) {
2172 verify_format(gmsgid);
2173 parse_error_inc();
2174 auto_diagnostic_group d;
2175 va_list ap;
2176 va_start (ap, gmsgid);
2177 rich_location richloc (line_table, token_location);
2178 /*bool ret =*/ global_dc->diagnostic_impl (&richloc, nullptr, option_zero,
2179 gmsgid, &ap, DK_ERROR);
2180 va_end (ap);
2181 }
2182
2183 extern int yychar;
2184 extern YYLTYPE yylloc;
2185
2186 /*
2187 * temp_loc_t is a hack in lieu of "%define parse.error custom". When
2188 * instantiated, if there is a lookahead token (or one is provided), it sets
2189 * the global token_location, which is passed to the diagnostic framework. The
2190 * original value is restored when the instantiated variable goes out of scope.
2191 */
2192 class temp_loc_t {
2193 location_t orig;
2194 public:
2195 temp_loc_t() : orig(token_location) {
2196 if( yychar < 3 ) return;
2197
2198 gcc_location_set(yylloc); // use lookahead location
2199 }
2200 explicit temp_loc_t( const YYLTYPE& loc) : orig(token_location) {
2201 gcc_location_set(loc);
2202 }
2203 explicit temp_loc_t( const YDFLTYPE& loc) : orig(token_location) {
2204 gcc_location_set(loc);
2205 }
2206 ~temp_loc_t() {
2207 if( orig != token_location ) {
2208 token_location = orig;
2209 }
2210 }
2211 };
2212
2213 /*
2214 * Both CDF and parser need to call error_msg, each with their own distinct
2215 * location type, not because they *need* to be different, but because they
2216 * are, as an artifact of using different prefixes. Possibly a better plan
2217 * would be to convert cdf.y to a pure parser, using no global variables. But
2218 * this is where we are.
2219 *
2220 * Because we can't reliably instantiate it as a forward-declared template
2221 * function, and because the paramters are variadic, we can't use a template
2222 * function or call one. So, a macro.
2223 */
2224
2225 #define ERROR_MSG_BODY \
2226 temp_loc_t looker(loc); \
2227 verify_format(gmsgid); \
2228 parse_error_inc(); \
2229 global_dc->begin_group(); \
2230 va_list ap; \
2231 va_start (ap, gmsgid); \
2232 rich_location richloc (line_table, token_location); \
2233 bool ret = global_dc->diagnostic_impl (&richloc, nullptr, option_zero, \
2234 gmsgid, &ap, DK_ERROR); \
2235 va_end (ap); \
2236 global_dc->end_group();
2237
2238
2239 void error_msg( const YYLTYPE& loc, const char gmsgid[], ... ) {
2240 ERROR_MSG_BODY
2241 }
2242
2243 void error_msg( const YDFLTYPE& loc, const char gmsgid[], ... )
2244 ATTRIBUTE_GCOBOL_DIAG(2, 3);
2245
2246 void error_msg( const YDFLTYPE& loc, const char gmsgid[], ... ) {
2247 ERROR_MSG_BODY
2248 }
2249
2250 bool
2251 warn_msg( const YYLTYPE& loc, const char gmsgid[], ... ) {
2252 temp_loc_t looker(loc);
2253 verify_format(gmsgid);
2254 auto_diagnostic_group d;
2255 va_list ap;
2256 va_start (ap, gmsgid);
2257 rich_location richloc (line_table, token_location);
2258 auto ret = emit_diagnostic_valist( DK_WARNING, token_location,
2259 option_zero, gmsgid, &ap );
2260 va_end (ap);
2261 return ret;
2262 }
2263
2264 void error_msg_direct( const char gmsgid[], ... ) {
2265 verify_format(gmsgid);
2266 parse_error_inc();
2267 auto_diagnostic_group d;
2268 va_list ap;
2269 va_start (ap, gmsgid);
2270 /*auto ret = */emit_diagnostic_valist( DK_ERROR, token_location,
2271 option_zero, gmsgid, &ap );
2272 va_end (ap);
2273 }
2274
2275 void
2276 yyerror( const char gmsgid[], ... ) {
2277 temp_loc_t looker;
2278 verify_format(gmsgid);
2279 parse_error_inc();
2280 global_dc->begin_group();
2281 va_list ap;
2282 va_start (ap, gmsgid);
2283 rich_location richloc (line_table, token_location);
2284 /*bool ret =*/ global_dc->diagnostic_impl ( &richloc,
2285 nullptr,
2286 option_zero,
2287 gmsgid,
2288 &ap, DK_ERROR);
2289 va_end (ap);
2290 global_dc->end_group();
2291 }
2292
2293 bool
2294 yywarn( const char gmsgid[], ... ) {
2295 verify_format(gmsgid);
2296 auto_diagnostic_group d;
2297 va_list ap;
2298 va_start (ap, gmsgid);
2299 auto ret = emit_diagnostic_valist( DK_WARNING, token_location,
2300 option_zero, gmsgid, &ap );
2301 va_end (ap);
2302 return ret;
2303 }
2304
2305 /*
2306 * Sometimes during parsing an error is noticed late. This message refers back
2307 * to an arbitrary file and line number.
2308 */
2309 void
2310 yyerrorvl( int line, const char *filename, const char fmt[], ... ) {
2311 verify_format(fmt);
2312 parse_error_inc();
2313 auto_diagnostic_group d; // not needed unless we can use global_dc
2314 char *msg;
2315 va_list ap;
2316
2317 va_start(ap, fmt);
2318 msg = xvasprintf(fmt, ap);
2319
2320 if( !filename ) filename = cobol_filename();
2321
2322 fprintf( stderr, "%s:%d: %s\n", filename, line, msg);
2323
2324 free(msg);
2325 va_end(ap);
2326 }
2327
2328 static inline size_t
2329 matched_length( const regmatch_t& rm ) { return rm.rm_eo - rm.rm_so; }
2330
2331 int
2332 cobol_fileline_set( const char line[] ) {
2333 static const char pattern[] = "#line +([[:alnum:]]+) +[\"']([^\"']+). *\n";
2334 static const int cflags = REG_EXTENDED | REG_ICASE;
2335 static regex_t re, *preg = NULL;
2336
2337 int erc;
2338 regmatch_t pmatch[4];
2339
2340 if( !preg ) {
2341 if( (erc = regcomp(&re, pattern, cflags)) != 0 ) {
2342 regerror(erc, &re, regexmsg, sizeof(regexmsg));
2343 dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
2344 return 0;
2345 }
2346 preg = &re;
2347 }
2348 if( (erc = regexec(preg, line, COUNT_OF(pmatch), pmatch, 0)) != 0 ) {
2349 if( erc != REG_NOMATCH ) {
2350 regerror(erc, preg, regexmsg, sizeof(regexmsg));
2351 dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
2352 return 0;
2353 }
2354 error_msg(yylloc, "invalid %<#line%> directive: %s", line );
2355 return 0;
2356 }
2357
2358 const char
2359 *line_str = xstrndup(line + pmatch[1].rm_so, matched_length(pmatch[1])),
2360 *filename = xstrndup(line + pmatch[2].rm_so, matched_length(pmatch[2]));
2361 int fileline;
2362
2363 if( 1 != sscanf(line_str, "%d", &fileline) )
2364 yywarn("could not parse line number %s from %<#line%> directive", line_str);
2365
2366 input_file_t input_file( filename, ino_t(0), fileline ); // constructor sets inode
2367
2368 if( input_filenames.empty() ) {
2369 input_filenames.push(input_file);
2370 }
2371
2372 input_file_t& file = input_filenames.top();
2373 file = input_file;
2374
2375 return file.lineno;
2376 }
2377
2378 //#define TIMING_PARSE
2379 #ifdef TIMING_PARSE
2380 class cbl_timespec {
2381 uint64_t now; // Nanoseconds
2382 public:
2383 cbl_timespec() {
2384 now = get_time_nanoseconds();
2385 }
2386 double ns() const {
2387 return now;
2388 }
2389 friend double operator-( const cbl_timespec& now, const cbl_timespec& then );
2390 };
2391
2392 double
2393 operator-( const cbl_timespec& now, const cbl_timespec& then ) {
2394 return (now.ns() - then.ns()) / 1000000000;
2395 }
2396 #endif
2397
2398 static int
2399 parse_file( const char filename[] )
2400 {
2401 if( (yyin = cdftext::lex_open(filename)) == NULL) {
2402 cbl_err("cannot open %s", filename);
2403 }
2404
2405 parser_enter_file(filename);
2406
2407 if( input_filenames.option() == 'M' ) {
2408 input_filenames.print();
2409 return 0;
2410 }
2411
2412 #ifdef TIMING_PARSE
2413 cbl_timespec start;
2414 #endif
2415
2416 int erc = yyparse();
2417
2418 #ifdef TIMING_PARSE
2419 cbl_timespec finish;
2420 double dt = finish - start;
2421 printf("Overall parse & generate time is %.6f seconds\n", dt);
2422 #endif
2423
2424 parser_leave_file();
2425
2426
2427 fclose (yyin);
2428
2429 if( erc ) {
2430 error_at (UNKNOWN_LOCATION, "failed compiling %s", filename);
2431 }
2432
2433 return erc;
2434 }
2435
2436 #pragma GCC diagnostic pop
2437
2438 extern int yy_flex_debug, yydebug, ydfdebug;
2439 extern int f_trace_debug;
2440
2441 void cobol_set_indicator_column( int column );
2442
2443 void
2444 cobol_set_debugging( bool flex, bool yacc, bool parser )
2445 {
2446 yy_flex_debug = flex? 1 : 0;
2447 ydfdebug = yydebug = yacc? 1 : 0;
2448 f_trace_debug = parser? 1 : 0;
2449 }
2450
2451 os_locale_t os_locale = { "UTF-8", "C.UTF-8" };
2452
2453 void
2454 cobol_parse_files (int nfile, const char **files)
2455 {
2456 const char * opaque = setlocale(LC_CTYPE, "");
2457 if( ! opaque ) {
2458 yywarn("setlocale: unable to initialize LOCALE");
2459 } else {
2460 char *codeset = nl_langinfo(CODESET);
2461 if( ! codeset ) {
2462 yywarn("%<nl_langinfo%> failed after %<setlocale()%> succeeded");
2463 } else {
2464 os_locale.codeset = codeset;
2465 }
2466 }
2467 assert(os_locale.codeset);
2468
2469 for (int i = 0; i < nfile; i++) {
2470 parse_file (files[i]);
2471 }
2472 }
2473
2474 /* Outputs the formatted string onto the file descriptor */
2475
2476 void
2477 cbl_message(int fd, const char *format_string, ...)
2478 {
2479 va_list ap;
2480 va_start(ap, format_string);
2481 char *ostring = xvasprintf(format_string, ap);
2482 va_end(ap);
2483 write(fd, ostring, strlen(ostring));
2484 write(fd, "\n", 1);
2485 free(ostring);
2486 }
2487
2488 /* Uses the GCC internal_error () to output the formatted string. Processing
2489 ends with a stack trace */
2490
2491 void
2492 cbl_internal_error(const char *gmsgid, ...) {
2493 verify_format(gmsgid);
2494 auto_diagnostic_group d;
2495 va_list ap;
2496 va_start(ap, gmsgid);
2497 emit_diagnostic_valist( DK_ICE, token_location, option_zero, gmsgid, &ap );
2498 va_end(ap);
2499 abort(); // This unnecessary statement is needed so that [[noreturn]]
2500 // // doesn't cause a warning.
2501 }
2502
2503 void
2504 cbl_unimplementedw(const char *gmsgid, ...) {
2505 verify_format(gmsgid);
2506 auto_diagnostic_group d;
2507 va_list ap;
2508 va_start(ap, gmsgid);
2509 emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
2510 va_end(ap);
2511 }
2512
2513 void
2514 cbl_unimplemented(const char *gmsgid, ...) {
2515 verify_format(gmsgid);
2516 auto_diagnostic_group d;
2517 va_list ap;
2518 va_start(ap, gmsgid);
2519 emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
2520 va_end(ap);
2521 }
2522
2523 void
2524 cbl_unimplemented_at( const YYLTYPE& loc, const char *gmsgid, ... ) {
2525 temp_loc_t looker(loc);
2526 verify_format(gmsgid);
2527 auto_diagnostic_group d;
2528 va_list ap;
2529 va_start(ap, gmsgid);
2530 emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
2531 va_end(ap);
2532 }
2533
2534 /*
2535 * analogs to err(3) and errx(3).
2536 */
2537
2538 #pragma GCC diagnostic push
2539 #pragma GCC diagnostic ignored "-Wformat"
2540 void
2541 cbl_err(const char *fmt, ...) {
2542 auto_diagnostic_group d;
2543 char *gmsgid = xasprintf("%m: %s", fmt);
2544 verify_format(gmsgid);
2545 va_list ap;
2546 va_start(ap, fmt);
2547 emit_diagnostic_valist( DK_FATAL, token_location, option_zero, gmsgid, &ap );
2548 va_end(ap);
2549 }
2550 #pragma GCC diagnostic pop
2551
2552 void
2553 cbl_errx(const char *gmsgid, ...) {
2554 verify_format(gmsgid);
2555 auto_diagnostic_group d;
2556 va_list ap;
2557 va_start(ap, gmsgid);
2558 emit_diagnostic_valist( DK_FATAL, token_location, option_zero, gmsgid, &ap );
2559 va_end(ap);
2560 }
2561
2562 void
2563 dbgmsg(const char *msg, ...) {
2564 if( yy_flex_debug || yydebug ) {
2565 fflush(stdout);
2566 va_list ap;
2567 va_start(ap, msg);
2568 vfprintf(stderr, msg, ap);
2569 fprintf(stderr, "\n");
2570 va_end(ap);
2571 }
2572 }
2573
2574 void
2575 dialect_error( const YYLTYPE& loc, const char term[], const char dialect[] ) {
2576 error_msg(loc, "%s is not ISO syntax, requires %<-dialect %s%>",
2577 term, dialect);
2578 }
2579
2580 bool fisdigit(int c)
2581 {
2582 return ISDIGIT(c);
2583 }
2584 bool fisspace(int c)
2585 {
2586 return ISSPACE(c);
2587 }
2588 int ftolower(int c)
2589 {
2590 return TOLOWER(c);
2591 }
2592 int ftoupper(int c)
2593 {
2594 return TOUPPER(c);
2595 }
2596 bool fisprint(int c)
2597 {
2598 return ISPRINT(c);
2599 }
2600
2601 // 8.9 Reserved words
2602 static const std::set<std::string> reserved_words = {
2603 // GCC COBOL keywords
2604 "COMMAND-LINE",
2605 "COMMAND-LINE-COUNT",
2606
2607 // GCC device names
2608 "C01",
2609 "C02",
2610 "C03",
2611 "C04",
2612 "C05",
2613 "C06",
2614 "C07",
2615 "C08",
2616 "C09",
2617 "C10",
2618 "C11",
2619 "C12",
2620 "CONSOLE",
2621 "S01",
2622 "S02",
2623 "S03",
2624 "S04",
2625 "S05",
2626 "STDERR",
2627 "STDIN",
2628 "STDOUT",
2629 "SYSIN",
2630 "SYSIPT",
2631 "SYSLIST",
2632 "SYSLST",
2633 "SYSOUT",
2634 "SYSPCH",
2635 "SYSPUNCH",
2636 "UPSI",
2637
2638 // IBM keywords that GCC recognizes
2639 "BASIS",
2640 "CBL",
2641 "ENTER",
2642 "READY",
2643 "TITLE",
2644 "TRACE",
2645 "ALTER",
2646 "COBOL",
2647 "DATE-COMPILED",
2648 "DATE-WRITTEN",
2649 "DBCS",
2650 "DEBUGGING",
2651 "EGCS",
2652 "ENTRY",
2653 "EVERY",
2654 "INSTALLATION",
2655 "I-O-CONTROL",
2656 "KANJI",
2657 "LABEL",
2658 "NULLS",
2659 "PADDING",
2660 "PROCEDURES",
2661 "PROCEED",
2662 "RECORDING",
2663 "RERUN",
2664 "REVERSED",
2665 "SECURITY",
2666 "TALLY",
2667 "VOLATILE",
2668 "XML",
2669 "END-START",
2670
2671 // ISO 2023 keywords
2672 "ACCEPT",
2673 "ACCESS",
2674 "ACTIVE-CLASS",
2675 "ADD",
2676 "ADDRESS",
2677 "ADVANCING",
2678 "AFTER",
2679 "ALIGNED",
2680 "ALL",
2681 "ALLOCATE",
2682 "ALPHABET",
2683 "ALPHABETIC",
2684 "ALPHABETIC-LOWER",
2685 "ALPHABETIC-UPPER",
2686 "ALPHANUMERIC",
2687 "ALPHANUMERIC-EDITED",
2688 "ALSO",
2689 "ALTERNATE",
2690 "AND",
2691 "ANY",
2692 "ANYCASE",
2693 "ARE",
2694 "AREA",
2695 "AREAS",
2696 "AS",
2697 "ASCENDING",
2698 "ASSIGN",
2699 "AT",
2700 "B-AND",
2701 "B-NOT",
2702 "B-OR",
2703 "B-SHIFT-L",
2704 "B-SHIFT-LC",
2705 "B-SHIFT-R",
2706 "B-SHIFT-RC",
2707 "B-XOR",
2708 "BASED",
2709 "BEFORE",
2710 "BINARY",
2711 "BINARY-CHAR",
2712 "BINARY-DOUBLE",
2713 "BINARY-LONG",
2714 "BINARY-SHORT",
2715 "BIT",
2716 "BLANK",
2717 "BLOCK",
2718 "BOOLEAN",
2719 "BOTTOM",
2720 "BY",
2721 "CALL",
2722 "CANCEL",
2723 "CF",
2724 "CH",
2725 "CHARACTER",
2726 "CHARACTERS",
2727 "CLASS",
2728 "CLASS-ID",
2729 "CLOSE",
2730 "CODE",
2731 "CODE-SET",
2732 "COL",
2733 "COLLATING",
2734 "COLS",
2735 "COLUMN",
2736 "COLUMNS",
2737 "COMMA",
2738 "COMMIT",
2739 "COMMON",
2740 "COMP",
2741 "COMPUTATIONAL",
2742 "COMPUTE",
2743 "CONDITION",
2744 "CONFIGURATION",
2745 "CONSTANT",
2746 "CONTAINS",
2747 "CONTENT",
2748 "CONTINUE",
2749 "CONTROL",
2750 "CONTROLS",
2751 "CONVERTING",
2752 "COPY",
2753 "CORR",
2754 "CORRESPONDING",
2755 "COUNT",
2756 "CRT",
2757 "CURRENCY",
2758 "CURSOR",
2759 "DATA",
2760 "DATA-POINTER",
2761 "DATE",
2762 "DAY",
2763 "DAY-OF-WEEK",
2764 "DE",
2765 "DECIMAL-POINT",
2766 "DECLARATIVES",
2767 "DEFAULT",
2768 "DELETE",
2769 "DELIMITED",
2770 "DELIMITER",
2771 "DEPENDING",
2772 "DESCENDING",
2773 "DESTINATION",
2774 "DETAIL",
2775 "DISPLAY",
2776 "DIVIDE",
2777 "DIVISION",
2778 "DOWN",
2779 "DUPLICATES",
2780 "DYNAMIC",
2781 "EC",
2782 "EDITING",
2783 "ELSE",
2784 "EMD-START",
2785 "END",
2786 "END-ACCEPT",
2787 "END-ADD",
2788 "END-CALL",
2789 "END-COMPUTE",
2790 "END-DELETE",
2791 "END-DISPLAY",
2792 "END-DIVIDE",
2793 "END-EVALUATE",
2794 "END-IF",
2795 "END-MULTIPLY",
2796 "END-OF-PAGE",
2797 "END-PERFORM",
2798 "END-READ",
2799 "END-RECEIVE",
2800 "END-RETURN",
2801 "END-REWRITE",
2802 "END-SEARCH",
2803 "END-SEND",
2804 "END-STRING",
2805 "END-SUBTRACT",
2806 "END-UNSTRING",
2807 "END-WRITE",
2808 "ENVIRONMENT",
2809 "EO",
2810 "EOP",
2811 "EQUAL",
2812 "ERROR",
2813 "EVALUATE",
2814 "EXCEPTION",
2815 "EXCEPTION-OBJECT",
2816 "EXCLUSIVE-OR",
2817 "EXIT",
2818 "EXTEND",
2819 "EXTERNAL",
2820 "FACTORY",
2821 "FALSE",
2822 "FARTHEST-FROM-ZERO",
2823 "FD",
2824 "FILE",
2825 "FILE-CONTROL",
2826 "FILLER",
2827 "FINAL",
2828 "FINALLY",
2829 "FIRST",
2830 "FLOAT-BINARY-128",
2831 "FLOAT-BINARY-32",
2832 "FLOAT-BINARY-64",
2833 "FLOAT-DECIMAL-16",
2834 "FLOAT-DECIMAL-34",
2835 "FLOAT-EXTENDED",
2836 "FLOAT-INFINITY",
2837 "FLOAT-LONG",
2838 "FLOAT-NOT-A-NUMBER-",
2839 "FLOAT-SHORT",
2840 "FOOTING",
2841 "FOR",
2842 "FORMAT",
2843 "FREE",
2844 "FROM",
2845 "FUNCTION",
2846 "FUNCTION-ID",
2847 "FUNCTION-POINTER",
2848 "GENERATE",
2849 "GET",
2850 "GIVING",
2851 "GLOBAL",
2852 "GO",
2853 "GOBACK",
2854 "GREATER",
2855 "GROUP",
2856 "GROUP-USAGE",
2857 "HEADING",
2858 "HIGH-VALUE",
2859 "HIGH-VALUES",
2860 "I-O",
2861 "I-OICONTROL",
2862 "IDENTIFICATION",
2863 "IF",
2864 "IN",
2865 "IN-ARITHMETIC-RANGE",
2866 "INDEX",
2867 "INDEXED",
2868 "INDICATE",
2869 "INHERITS",
2870 "INITIAL",
2871 "INITIALIZE",
2872 "INITIATE",
2873 "INPUT",
2874 "INPUT-OUTPUT",
2875 "INSPECT",
2876 "INTERFACE",
2877 "INTERFACE-ID",
2878 "INTO",
2879 "INVALID",
2880 "INVOKE",
2881 "IS",
2882 "JUST",
2883 "JUSTIFIED",
2884 "KEY",
2885 "LAST",
2886 "LEADING",
2887 "LEFT",
2888 "LENGTH",
2889 "LESS",
2890 "LIMIT",
2891 "LIMITS",
2892 "LINAGE",
2893 "LINAGE-COUNTER",
2894 "LINE",
2895 "LINE-COUNTER",
2896 "LINES",
2897 "LINKAGE",
2898 "LOCAL-STORAGE",
2899 "LOCALE",
2900 "LOCATION",
2901 "LOCK",
2902 "LOW-VALUE",
2903 "LOW-VALUES",
2904 "MERGE",
2905 "MESSAGE-TAG",
2906 "METHOD-ID",
2907 "MINUS",
2908 "MODE",
2909 "MOVE",
2910 "MULTIPLY",
2911 "NATIONAL",
2912 "NATIONAL-EDITED",
2913 "NATIVE",
2914 "NEAREST-TO-ZERO",
2915 "NEGATIVE",
2916 "NESTED",
2917 "NEXT",
2918 "NO",
2919 "NOT",
2920 "NULL",
2921 "NUMBER",
2922 "NUMERIC",
2923 "NUMERIC-EDITED",
2924 "OBJECT",
2925 "OBJECT-COMPUTER",
2926 "OBJECT-REFERENCE",
2927 "OCCURS",
2928 "OF",
2929 "OFF",
2930 "OMITTED",
2931 "ON",
2932 "OPEN",
2933 "OPTIONAL",
2934 "OPTIONS",
2935 "OR",
2936 "ORDER",
2937 "ORGANIZATION",
2938 "OTHER",
2939 "OUTPUT",
2940 "OVERFLOW",
2941 "OVERRIDE",
2942 "PACKED-DECIMAL",
2943 "PAGE",
2944 "PAGE-COUNTER",
2945 "PERFORM",
2946 "PF",
2947 "PH",
2948 "PIC",
2949 "PICTURE",
2950 "PLUS",
2951 "POINTER",
2952 "POSITIVE",
2953 "PRESENT",
2954 "PRINTING",
2955 "PROCEDURE",
2956 "PROGRAM",
2957 "PROGRAM-ID",
2958 "PROGRAM-POINTER",
2959 "PROPERTY",
2960 "PROTOTYPE",
2961 "QUIET",
2962 "QUOTE",
2963 "QUOTES",
2964 "RAISE",
2965 "RAISING",
2966 "RANDOM",
2967 "RD",
2968 "READ",
2969 "RECEIVE",
2970 "RECORD",
2971 "RECORDS",
2972 "REDEFINES",
2973 "REEL",
2974 "REFERENCE",
2975 "RELATIVE",
2976 "RELEASE",
2977 "REMAINDER",
2978 "REMOVAL",
2979 "RENAMES",
2980 "REPLACE",
2981 "REPLACING",
2982 "REPORT",
2983 "REPORTING",
2984 "REPORTS",
2985 "REPOSITORY",
2986 "RESERVE",
2987 "RESET",
2988 "RESUME",
2989 "RETRY",
2990 "RETURN",
2991 "RETURNING",
2992 "REWIND",
2993 "REWRITE",
2994 "RF",
2995 "RH",
2996 "RIGHT",
2997 "ROLLBACK",
2998 "ROUNDED",
2999 "RUN",
3000 "SAME",
3001 "SCREEN",
3002 "SD",
3003 "SEARCH",
3004 "SECTION",
3005 "SELECT",
3006 "SELF",
3007 "SEND",
3008 "SENTENCE",
3009 "SEPARATE",
3010 "SEQUENCE",
3011 "SEQUENTIAL",
3012 "SET",
3013 "SHARING",
3014 "SIGN",
3015 "SIGNALING",
3016 "SIZE",
3017 "SORT",
3018 "SORT-MERGE",
3019 "SOURCE",
3020 "SOURCE-COMPUTER",
3021 "SOURCES",
3022 "SPACE",
3023 "SPACES",
3024 "SPECIAL-NAMES",
3025 "STANDARD",
3026 "STANDARD-1",
3027 "STANDARD-2",
3028 "START",
3029 "STATUS",
3030 "STOP",
3031 "STRING",
3032 "SUBTRACT",
3033 "SUM",
3034 "SUPER",
3035 "SUPPRESS",
3036 "SYMBOLIC",
3037 "SYNC",
3038 "SYNCHRONIZED",
3039 "SYSTEM-DEFAULT",
3040 "TABLE",
3041 "TALLYING",
3042 "TERMINATE",
3043 "TEST",
3044 "THAN",
3045 "THEN",
3046 "THROUGH",
3047 "THRU",
3048 "TIME",
3049 "TIMES",
3050 "TO",
3051 "TOP",
3052 "TRAILING",
3053 "TRUE",
3054 "TYPE",
3055 "TYPEDEF",
3056 "UNIT",
3057 "UNIVERSAL",
3058 "UNLOCK",
3059 "UNSTRING",
3060 "UNTIL",
3061 "UP",
3062 "UPON",
3063 "USAGE",
3064 "USE",
3065 "USER-DEFAULT",
3066 "USING",
3067 "VAL-STATUS",
3068 "VALID",
3069 "VALIDATE",
3070 "VALIDATE-STATUS",
3071 "VALUE",
3072 "VALUES",
3073 "VARYING",
3074 "WHEN",
3075 "WITH",
3076 "WORKING-STORAGE",
3077 "WRITE",
3078 "XOR",
3079 "ZERO",
3080 "ZEROES",
3081 "ZEROS",
3082 "+",
3083 "-",
3084 "*",
3085 "/",
3086 "**",
3087 "<",
3088 "<=",
3089 "<>",
3090 "=",
3091 ">",
3092 ">=",
3093 "&",
3094 "*>",
3095 "::",
3096 ">>",
3097 };
3098
3099 // 8.10 Context-sensitive words
3100 static const std::set<std::string> context_sensitive_words = {
3101 "ACTIVATING", // MODULE-NAME intrinsic function
3102 "ANUM", // CONVERT intrinsic function
3103 "APPLY", // I-O-CONTROL paragraph
3104 "ARITHMETIC", // OPTIONS paragraph
3105 "ATTRIBUTE", // SET statement
3106 "AUTO", // screen description entry
3107 "AUTOMATIC", // LOCK MODE clause
3108 "AWAY-FROM-ZERO", // ROUNDED phrase
3109 "BACKGROUND-COLOR", // screen description entry
3110 "BACKWARD", // INSPECT statement
3111 "BELL", // screen description entry and SET attribute statement
3112 "BINARY-ENCODING", // USAGE clause and FLOAT-DECIMAL clause
3113 "BLINK", // screen description entry and SET attribute statement
3114 "BYTE", // CONVERT intrinsic function
3115 "BYTES", // RECORD clause
3116 "BYTE-LENGTH", // constant entry
3117 "CAPACITY", // OCCURS clause
3118 "CENTER", // COLUMN clause
3119 "CLASSIFICATION", // OBJECT-COMPUTER paragraph
3120 "CURRENT", // MODULE-NAME intrinsic function
3121 "CYCLE", // EXIT statement
3122 "DECIMAL-ENCODING", // USAGE clause and FLOAT-DECIMAL clause
3123 "EOL", // ERASE clause in a screen description entry
3124 "EOS", // ERASE clause in a screen description entry
3125 "ENTRY-CONVENTION", // OPTIONS paragraph
3126 "ERASE", // screen description entry
3127 "EXPANDS", // class-specifier and interface-specifier of the REPOSITORY paragraph
3128 "FLOAT-BINARY", // OPTIONS paragraph
3129 "FLOAT-DECIMAL", // OPTIONS paragraph
3130 "FOREGROUND-COLOR", // screen description entry
3131 "FOREVER", // RETRY phrase
3132 "FULL", // screen description entry
3133 "HEX", // CONVERT intrinsic function
3134 "HIGH-ORDER-LEFT", // FLOAT-BINARY clause, FLOAT-DECIMAL clause, and USAGE clause
3135 "HIGH-ORDER-RIGHT", // FLOAT-BINARY clause, FLOAT-DECIMAL clause, and USAGE clause
3136 "HIGHLIGHT", // screen description entry and SET attribute statement
3137 "IGNORING", // READ statement
3138 "IMPLEMENTS", // FACTORY paragraph and OBJECT paragraph
3139 "INITIALIZED", // ALLOCATE statement and OCCURS clause
3140 "INTERMEDIATE", // OPTIONS paragraph
3141 "INTRINSIC", // function-specifier of the REPOSITORY paragraph
3142 "LC_ALL", // SET statement
3143 "LC_COLLATE", // SET statement
3144 "LC_CTYPE", // SET statement
3145 "LC_MESSAGES", // SET statement
3146 "LC_MONETARY", // SET statement
3147 "LC_NUMERIC", // SET statement
3148 "LC_TIME", // SET statement
3149 "LOWLIGHT", // screen description entry and SET attribute statement
3150 "MANUAL", // LOCK MODE clause
3151 "MULTIPLE", // LOCK ON phrase
3152 "NAT", // CONVERT intrinsic function
3153 "NEAREST-AWAY-FROM-ZERO", // INTERMEDIATE ROUNDING clause and ROUNDED phrase
3154 "NEAREST-EVEN", // INTERMEDIATE ROUNDING clause and ROUNDED phrase
3155 "NEAREST-TOWARD-ZERO", // INTERMEDIATE ROUNDING clause and ROUNDED phrase
3156 "NONE", // DEFAULT clause
3157 "NORMAL", // STOP statement
3158 "NUMBERS", // COLUMN clause and LINE clause
3159 "ONLY", // Object-view, SHARING clause, SHARING phrase, and USAGE clause
3160 "PARAGRAPH", // EXIT statement
3161 "PREFIXED", // DYNAMIC LENGTH STRUCTURE clause
3162 "PREVIOUS", // READ statement
3163 "PROHIBITED", // INTERMEDIATE ROUNDING clause and ROUNDED phrase
3164 "RECURSIVE", // PROGRAM-ID paragraph
3165 "RELATION", // VALIDATE-STATUS clause
3166 "REQUIRED", // screen description entry
3167 "REVERSE-VIDEO", // screen description entry and SET attribute statement
3168 "ROUNDING", // OPTIONS paragraph
3169 "SECONDS", // RETRY phrase, CONTINUE statement
3170 "SECURE", // screen description entry
3171 "SHORT", // DYNAMIC LENGTH STRUCTURE clause
3172 "SIGNED", // DYNAMIC LENGTH STRUCTURE clause and USAGE clause
3173 "STACK", // MODULE-NAME intrinsic function
3174 "STANDARD-BINARY", // ARITHMETIC clause
3175 "STANDARD-DECIMAL", // ARITHMETIC clause
3176 "STATEMENT", // RESUME statement
3177 "STEP", // OCCURS clause
3178 "STRONG", // TYPEDEF clause
3179 "STRUCTURE", // DYNAMIC LENGTH STRUCTURE clause
3180 "SYMBOL", // CURRENCY clause
3181 "TOP-LEVEL", // MODULE-NAME intrinsic function
3182 "TOWARD-GREATER", // ROUNDED phrase
3183 "TOWARD-LESSER", // ROUNDED phrase
3184 "TRUNCATION", // INTERMEDIATE ROUNDING clause and ROUNDED phrase
3185 "UCS-4", // ALPHABET clause
3186 "UNDERLINE", // screen description entry and SET attribute statement
3187 "UNSIGNED", // USAGE clause
3188 "UTF-8", // ALPHABET clause
3189 "UTF-16", // ALPHABET clause
3190 "YYYYDDD", // ACCEPT statement
3191 "YYYYMMDD", // ACCEPT statement
3192 };
3193
3194 // Is the input a COBOL word, per ISO/IEC 1989:2023 (E) ?
3195 // We add a few GCC-specific keywords, and our supported IBM keywords.
3196 bool
3197 iso_cobol_word( const std::string& name, bool include_context ) {
3198 auto ok = 1 == reserved_words.count(name);
3199 if( include_context && !ok ) {
3200 ok = 1 == context_sensitive_words.count(name);
3201 }
3202 return ok;
3203 }
3204