Debian Codegraph @

gcc/cobol/symbols.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 <fstream> // Before cobol-system because it uses poisoned functions
33 #include "cobol-system.h"
34
35 #include "coretypes.h"
36 #include "tree.h"
37
38 #include <search.h>
39 #include <iconv.h>
40 #include "../../libgcobol/ec.h"
41 #include "../../libgcobol/common-defs.h"
42 #include "util.h"
43 #include "cbldiag.h"
44 #include "symbols.h"
45 #include "inspect.h"
46 #include "../../libgcobol/io.h"
47 #include "genapi.h"
48
49 #pragma GCC diagnostic ignored "-Wunused-result"
50 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
51
52 bool
53 lexio_dialect_mf() { return dialect_mf(); }
54
55 class symbol_pair_t
56 {
57 const symbol_elem_t *first, *last;
58 public:
59 explicit symbol_pair_t( const symbol_elem_t * first, const symbol_elem_t * end = NULL )
60 : first(first), last(end)
61 {}
62
63 // used only by std::find to locate a pointer between first and last
64 bool operator==( const symbol_pair_t& that ) const {
65 return this->first <= that.first && that.first < this->last;
66 }
67
68 size_t index( const symbol_elem_t *psym ) const {
69 assert( first <= psym && psym < last );
70 return psym - first;
71 }
72 };
73
74 static std::map<size_t, YYLTYPE> field_locs;
75
76 void
77 symbol_field_location( size_t ifield, const YYLTYPE& loc ) {
78 gcc_assert(field_at(ifield));
79 field_locs[ifield] = loc;
80 }
81 YYLTYPE
82 symbol_field_location( size_t ifield ) {
83 auto p = field_locs.find(ifield);
84 gcc_assert(p != field_locs.end());
85 return p->second;
86 }
87
88 static struct symbol_table_t {
89 int fd;
90 size_t capacity, nelem;
91 size_t first_program, procedures;
92 struct registers_t {
93 size_t file_status, linage_counter, return_code,
94 exception_condition, very_true, very_false;
95 registers_t() {
96 file_status = linage_counter = return_code =
97 exception_condition = very_true = very_false = 0;
98 }
99 } registers;
100
101 struct symbol_elem_t *elems;
102
103 std::map<elem_key_t, size_t> specials;
104 std::map<elem_key_t, std::list<size_t>> labels;
105
106 std::vector<symbol_pair_t> mappings;
107
108 symbol_table_t()
109 : fd(-1)
110 , capacity(0), nelem(0), first_program(0), procedures(0)
111 , elems(NULL)
112 {}
113
114 /*
115 * To compute an offset into the symbol table from an element
116 * pointer, first search the mappings to determine which one it
117 * belongs to.
118 */
119 size_t index( const symbol_elem_t * psym ) const {
120 assert(psym);
121 auto pend = mappings.end();
122 auto p = std::find(mappings.begin(), pend, symbol_pair_t(psym));
123 assert( p != pend ); // pysm does not point to a symbol in the symbol table.
124 return p->index(psym);
125 }
126
127 void save() { mappings.push_back( symbol_pair_t( elems, elems + capacity ) ); }
128
129 size_t size() const { return capacity * sizeof(elems[0]); }
130
131 void labelmap_add( const symbol_elem_t *e ) {
132 const char *name = cbl_label_of(e)->name;
133 labels[ elem_key_t(e->program, name) ].push_back( symbol_index(e) );
134 }
135 } symbols;
136
137 static symbol_table_t&
138 symbol_table_extend() {
139
140 if( symbols.nelem == 0 ) { // first time: create file & set initial capacity
141 FILE *mapped;
142 if( (mapped = tmpfile()) == NULL ) {
143 cbl_err( "could not create temporary file for symbol table");
144 }
145
146 symbols.fd = fileno(mapped);
147 assert(symbols.fd > 0);
148
149 symbols.capacity = 64;
150 } else {
151 if( 0 != msync(symbols.elems, symbols.size(), MS_SYNC | MS_INVALIDATE) ) {
152 cbl_err( "%s:%d: could not synchronize symbol table with mapped file",
153 __func__, __LINE__ );
154 }
155 }
156
157 symbols.capacity *= 2;
158 off_t len = symbols.size();
159
160 if( 0 != ftruncate(symbols.fd, len) ) {
161 cbl_err( "%s:%d: could not extend symbol table to %lu elements",
162 __func__, __LINE__, gb4(symbols.capacity));
163 }
164
165 /*
166 * We never unmap a disused symbol table, to avoid referencing
167 * invalid pointers. The table itself contains no pointers; it uses
168 * table indexes. But the parser API uses pointers, and sometimes
169 * the table needs to be extended before the code generator is done
170 * with them.
171 *
172 * By extending the file and mapping it anew, the old mapping
173 * remains valid, and the new mapping extends it in a different part
174 * of the virtual address space. Page 0 of the old map, for example,
175 * occupies the same physical RAM as before, but is shared between
176 * two mappings.
177 */
178
179 void *mem = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, symbols.fd, 0);
180
181 if( MAP_FAILED == mem ) {
182 cbl_err( "%s:%d: could not extend symbol table", __func__, __LINE__);
183 }
184 symbols.elems = static_cast<struct symbol_elem_t*>(mem);
185
186 symbols.save(); // add new mapping to list of mappings
187
188 return symbols;
189 }
190
191 static struct symbol_elem_t *
192 symbol_at_impl( size_t index, bool internal = true ) {
193 assert( index <= symbols.nelem );
194 if( !internal ) assert( index < symbols.nelem );
195 symbol_elem_t *e = symbols.elems + index;
196
197 if( index == symbols.nelem ) return e;
198
199 if( e->type == SymField && cbl_field_of(e)->type == FldForward ) {
200 return symbol_field(e->program,
201 cbl_field_of(e)->parent, cbl_field_of(e)->name);
202 }
203 return e;
204 }
205
206 struct symbol_elem_t *
207 symbol_at( size_t index ) {
208 return symbol_at_impl(index, false);
209 }
210
211 static char decimal_point = '.';
212
213 size_t file_status_register() { return symbols.registers.file_status; }
214 size_t return_code_register() { return symbols.registers.return_code; }
215 size_t very_true_register() { return symbols.registers.very_true; }
216 size_t very_false_register() { return symbols.registers.very_false; }
217 size_t ec_register() { return symbols.registers.exception_condition; }
218
219 cbl_refer_t *
220 cbl_refer_t::empty() {
221 static cbl_refer_t empty;
222 return &empty;
223 }
224
225 cbl_field_t *
226 cbl_span_t::from_field() { assert(from); return from->field; }
227 cbl_field_t *
228 cbl_span_t::len_field() { assert(len); return len->field; }
229
230 cbl_ffi_arg_t::cbl_ffi_arg_t()
231 : optional(false)
232 , crv(by_reference_e)
233 , attr(none_of_e)
234 {}
235
236 cbl_ffi_arg_t::
237 cbl_ffi_arg_t( cbl_refer_t* refer, cbl_ffi_arg_attr_t attr )
238 : optional(false)
239 , crv(by_reference_e)
240 , attr(attr)
241 , refer(refer? *refer : cbl_refer_t())
242 {
243 if( refer && refer != refer->empty() ) delete refer;
244 }
245
246 cbl_ffi_arg_t::
247 cbl_ffi_arg_t( cbl_ffi_crv_t crv,
248 cbl_refer_t* refer, cbl_ffi_arg_attr_t attr )
249 : optional(false)
250 , crv(crv)
251 , attr(attr)
252 , refer(refer? *refer : cbl_refer_t())
253 {
254 if( refer && refer != refer->empty() ) delete refer;
255 }
256
257 #define ERROR_FIELD(F, ...) \
258 do{ \
259 auto loc = symbol_field_location(field_index(F)); \
260 error_msg(loc, __VA_ARGS__); \
261 } while(0)
262
263
264 static const struct cbl_occurs_t nonarray = cbl_occurs_t();
265
266 #if 0
267 # define CONSTANT_E constant_e
268 #else
269 # define CONSTANT_E intermediate_e
270 #endif
271
272
273 class group_size_t {
274 size_t size;
275 public:
276 group_size_t() : size(0) {}
277 group_size_t& operator+( const cbl_field_t& field ) {
278 size += field.data.capacity;
279 return *this;
280 }
281 size_t capacity() const { return size; }
282 };
283
284 enum { constq = constant_e | quoted_e };
285
286 static symbol_elem_t
287 elementize( const cbl_field_t& field ) {
288 symbol_elem_t sym (SymField);
289 sym.elem.field = field;
290 return sym;
291 }
292
293 size_t
294 field_index( const cbl_field_t *f ) {
295 assert(f);
296 return symbol_index(symbol_elem_of(f));
297 }
298
299 static inline bool
300 is_forward( const struct symbol_elem_t *e ) {
301 return cbl_field_of(e)->type == FldForward;
302 }
303 static inline bool
304 is_forward( const cbl_field_t *field ) {
305 return field->type == FldForward;
306 }
307
308 static inline bool
309 has_parent( const struct symbol_elem_t *e ) {
310 return cbl_field_of(e)->parent > 0;
311 }
312
313 /*
314 * A field is global if it's marked global, or if any of its parents are.
315 * Actually, only 01 level can be global, but this works.
316 */
317 bool
318 is_global( const cbl_field_t * field ) {
319 do {
320 if( (field->attr & global_e) == global_e ) {
321 return true;
322 }
323 if( field->parent > 0 ) {
324 symbol_elem_t *e = symbol_at(field->parent);
325 if( SymField == e->type ) {
326 field = cbl_field_of(e);
327 continue;
328 }
329 }
330 break;
331 } while(true);
332 return false;
333 }
334
335 static bool
336 special_pair_cmp( const cbl_special_name_t& key,
337 const cbl_special_name_t& elem ) {
338 const bool matched = key.id == elem.id || 0 == strcasecmp(key.name, elem.name);
339
340 return matched;
341 }
342
343 /*
344 * On insertion, a label may be a definition or a forward reference.
345 * On reference, a label may be qualified or not. If not, we don't
346 * know if it refers to a section or a paragraph.
347 *
348 * Declarations and references always use line == 0; only definitions
349 * have a line number.
350 *
351 * An unqualified reference is denoted LblNone. If not found, it is
352 * inserted as a declaration: LblNone, line 0.
353 *
354 * A qualified reference is denoted LblParagraph with a section, and
355 * with line = 0. A qualified reference updates an unqualified
356 * declaration; the declation is upgraded to LblParagraph with the
357 * section as its parent, but still with no line (because it's still
358 * undefined).
359 *
360 * Matching rules (assuming names match):
361 * Key Element New Effect
362 * type parent line type parent type
363 * None - None - unqualified ref matches decl
364 * None - Sect - unqualified ref matches section
365 * None - Para x unqualified ref matches any para
366 * Sect - None - Sect section definition updates decl
367 * Sect - Sect - section matches section
368 * Para S 0 None - Para S qualified ref updates decl
369 * Para x >0 None - Para paragraph definition updates decl
370 * Para S 0 Para S qualified ref matches decl or def
371 * Para x >0 Para x Para paragraph definition updates decl
372 * if elem.line == 0.
373 *
374 * All other combinations fail or are invalid by assertion.
375 */
376 static bool label_cmp( const cbl_label_t& key,
377 const cbl_label_t& elem, bool names_matched = false ) {
378 if( ! names_matched ) {
379 if( 0 != strcasecmp(key.name, elem.name) ) return false;
380 }
381
382 switch( key.type ) {
383
384 case LblNone:
385 assert(0 == key.explicit_parent());
386 assert(0 == key.line);
387 switch( elem.type ) {
388 case LblNone:
389 case LblSection:
390 assert(!elem.explicit_parent());
391 return true;
392 break;
393 case LblParagraph:
394 return true;
395 break;
396 default:
397 break;
398 }
399 break;
400
401 case LblSection:
402 assert(0 == key.explicit_parent());
403 switch( elem.type ) {
404 case LblNone:
405 case LblSection:
406 assert(!elem.explicit_parent());
407 return true;
408 break;
409 default:
410 break;
411 }
412 break;
413
414 case LblParagraph:
415 switch( elem.type ) {
416 case LblNone:
417 if(elem.explicit_parent()) {
418 cbl_errx( "%s:%d: LblNone '%s' has parent #%zu",
419 __func__, __LINE__, elem.name, elem.parent );
420 }
421 assert(!elem.explicit_parent());
422 return true;
423 break;
424 case LblParagraph:
425 if( key.parent == elem.parent ) { // explicit or implicit
426 return key.line == 0 || elem.line == 0 || key.line == elem.line;
427 // negative key.line never matches (causing insertion)
428 }
429 break;
430 default:
431 break;
432 }
433 break;
434 default:
435 gcc_unreachable();
436 }
437 return false;
438 }
439
440 static int
441 symbol_elem_cmp( const void *K, const void *E )
442 {
443 const struct symbol_elem_t
444 *k=static_cast<const struct symbol_elem_t *>(K),
445 *e=static_cast<const struct symbol_elem_t *>(E);
446
447 if( k->type != e->type ) return 1;
448 if( k->program != e->program && !is_program(*k)) return 1;
449
450 switch( k->type ) {
451 case SymFilename:
452 return strcmp(k->elem.filename, e->elem.filename);
453 break;
454 case SymDataSection:
455 return k->elem.section.type == e->elem.section.type ? 0 : 1;
456 break;
457 case SymField:
458 if( has_parent(k) && cbl_field_of(k)->parent != cbl_field_of(e)->parent ) {
459 return 1;
460 }
461 // If the key has attributes, they must match.
462 if( (cbl_field_of(k)->attr & global_e) == global_e ) {
463 if( !is_global(cbl_field_of(e)) ) {
464 return 1;
465 }
466 }
467 // forwards match forwards only
468 if( is_forward(k) && !is_forward(e) ) return 1;
469 if( !is_forward(k) && is_forward(e) ) return 1;
470 break;
471 case SymLabel:
472 // A LblNone element (created by a forward reference) that lacks a parent
473 // matches on name only. It becomes a LblParagraph or LblSection.
474 // Remember: this test is for adding labels, not resolving references.
475 {
476 const cbl_label_t& key = *cbl_label_of(k);
477 const cbl_label_t& elem = *cbl_label_of(e);
478
479 if( key.type != elem.type ) {
480 if( !(key.type == LblNone || elem.type == LblNone) ) return 1;
481 }
482
483 switch(key.type) {
484 case LblProgram: // There are no forward program labels
485 if( key.parent > 0 && key.parent != elem.parent ) return 1;
486 assert(key.parent == elem.parent || key.parent == 0);
487 break;
488 case LblNone: case LblSection: case LblParagraph:
489 return label_cmp(key, elem)? 0 : 1;
490 break;
491 default:
492 if( key.parent != elem.parent ) { // allow zero parent of LblNone
493 if( !(elem.type == LblNone && elem.explicit_parent() == 0) ) return 1;
494 }
495 assert(key.parent == elem.parent || elem.type == LblNone);
496 }
497
498 if( key.os_name && elem.os_name ) {
499 if( 0 == strcasecmp(key.os_name, elem.os_name) ) return 0; // success
500 }
501 return strcasecmp(key.name, elem.name);
502 }
503 // break; // This break not needed if all options do a return.
504 case SymSpecial:
505 return special_pair_cmp(k->elem.special, e->elem.special)? 0 : 1;
506 // break; // This break not needed after return.
507 case SymAlphabet:
508 return strcasecmp(k->elem.alphabet.name, e->elem.alphabet.name);
509 // break; // This break not needed after return.
510 case SymFile:
511 // If the key is global, so must be the found element.
512 if( (cbl_file_of(k)->attr & global_e) == global_e &&
513 (cbl_file_of(e)->attr & global_e) != global_e ) {
514 return 1;
515 }
516 return strcasecmp(k->elem.file.name, e->elem.file.name);
517 // break; // This break not needed after return.
518 }
519 assert(k->type == SymField);
520
521 #if 1
522 // Used by symbol_literalA
523 // Literals have no name. They match on their constant initial value.
524 if( is_literal(cbl_field_of(k)) && is_literal(cbl_field_of(e)) ) {
525 return strcmp(cbl_field_of(k)->data.initial, cbl_field_of(e)->data.initial);
526 }
527 #endif
528 if( cbl_field_of(k)->has_attr(filler_e) ) {
529 return 1; // filler never matches
530 }
531
532 return strcasecmp(cbl_field_of(k)->name, cbl_field_of(e)->name);
533 }
534
535 cbl_label_ref_t::
536 cbl_label_ref_t( size_t program, const cbl_label_t& context, int line,
537 const char name[], size_t isect )
538 : qualified(isect != 0)
539 , context(context)
540 , line(line)
541 , handle(NULL)
542 {
543 cbl_label_type_t type = isect? LblParagraph : LblNone;
544 struct cbl_label_t label = { type, isect, line };
545 assert(strlen(name) < sizeof(label.name));
546 strcpy(label.name, name);
547
548 target = symbol_label_add(program, &label);
549 assert(target);
550 }
551
552 struct cbl_label_t *
553 symbol_label( size_t program, cbl_label_type_t type, size_t section,
554 const char name[],
555 const char os_name[] )
556 {
557 static cbl_name_t lname;
558 std::transform(name, name + strlen(name) + 1, lname, tolower);
559 elem_key_t key( program, lname );
560 auto p = symbols.labels.find(key);
561 if( p == symbols.labels.end()) return NULL;
562
563 cbl_label_t protolabel = { type, section };
564 protolabel.os_name = os_name;
565 assert(strlen(name) < sizeof protolabel.name);
566 strcpy(protolabel.name, name);
567
568 const std::list<size_t>& syms(p->second);
569 auto psym =
570 std::find_if( syms.begin(), syms.end(),
571 [key=protolabel]( size_t isym ) {
572 const auto& elem = *cbl_label_of(symbol_at(isym));
573
574 switch(key.type) {
575 case LblProgram: // There are no forward program labels
576 if( key.parent > 0 && key.parent != elem.parent ) return false;
577 assert(key.parent == elem.parent || key.parent == 0);
578 break;
579 case LblNone: case LblSection: case LblParagraph:
580 return label_cmp(key, elem, true);
581 break;
582 default:
583 if( key.parent != elem.parent ) { // allow zero parent of LblNone
584 if( !(elem.type == LblNone && elem.explicit_parent() == 0) ) return false;
585 }
586 assert(key.parent == elem.parent || elem.type == LblNone);
587 break;
588 }
589
590 if( key.os_name && elem.os_name ) {
591 if( 0 == strcasecmp(key.os_name, elem.os_name) ) return true; // success
592 }
593 return true;
594 } );
595 if( psym == syms.end() ) return NULL;
596 return cbl_label_of(symbol_at(*psym));
597 }
598
599 size_t
600 symbol_label_id( const cbl_label_t *label ) {
601 auto e = symbol_elem_of(label);
602 size_t label_index = symbol_index(e);
603 assert( label_index < std::numeric_limits<uint32_t>::max() );
604 return label_index;
605 }
606
607 struct cbl_label_t *
608 symbol_program( size_t parent, const char name[] )
609 {
610 cbl_label_t label = {};
611 label.type = LblProgram;
612 label.parent = parent;
613 assert(strlen(name) < sizeof label.name);
614 strcpy(label.name, name);
615
616 struct symbol_elem_t key( SymLabel, 0 ), *e;
617 key.elem.label = label;
618
619 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
620 &symbols.nelem, sizeof(key),
621 symbol_elem_cmp ) );
622 return e? cbl_label_of(e) : NULL;
623 }
624
625 extern int yydebug;
626
627 static size_t
628 symbols_dump( size_t first, bool header );
629
630 struct symbol_elem_t *
631 symbol_function( size_t parent, const char name[] )
632 {
633 auto p = std::find_if( symbols_begin(), symbols_end(),
634 [parent, name]( const auto& elem ) {
635 if( elem.type == SymLabel ) {
636 auto L = cbl_label_of(&elem);
637 if( L->type == LblFunction ) {
638 return 0 == strcasecmp(L->name, name);
639 }
640 }
641 return false;
642 } );
643
644 if( yydebug && p == symbols_end() ) symbols_dump( symbols.first_program, true);
645
646 return p == symbols_end()? NULL : p;
647
648 cbl_label_t label = {};
649 label.type = LblFunction;
650 label.parent = parent;
651 assert(strlen(name) < sizeof label.name);
652 strcpy(label.name, name);
653
654 struct symbol_elem_t key(SymLabel, 0), *e;
655 key.elem.label = label;
656
657 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
658 &symbols.nelem, sizeof(key),
659 symbol_elem_cmp ) );
660 return e;
661 }
662
663 struct symbol_elem_t *
664 symbol_special( size_t program, const char name[] )
665 {
666 elem_key_t key( program, name );
667 auto p = symbols.specials.find(key);
668 if( p == symbols.specials.end() ) return NULL;
669 return symbol_at(p->second);
670 }
671
672 struct symbol_elem_t *
673 symbol_alphabet( size_t program, const char name[] )
674 {
675 cbl_alphabet_t alphabet(YYLTYPE(), custom_encoding_e); // cppcheck-suppress syntaxError
676 assert(strlen(name) < sizeof alphabet.name);
677 strcpy(alphabet.name, name);
678
679 struct symbol_elem_t key(SymAlphabet, program), *e;
680 key.elem.alphabet = alphabet;
681
682 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
683 &symbols.nelem, sizeof(key),
684 symbol_elem_cmp ) );
685 return e;
686 }
687
688 symbol_elem_t *
689 symbols_begin( size_t first )
690 {
691 return symbols.elems + first;
692 }
693
694 symbol_elem_t *
695 symbols_end(void)
696 {
697 return symbols.elems + symbols.nelem;
698 }
699
700 cbl_field_t *
701 symbol_redefines( const struct cbl_field_t *field ) {
702 if( field->parent == 0 ) return NULL;
703 struct symbol_elem_t *e = symbol_at(field->parent);
704 if( e->type == SymField ) {
705 cbl_field_t *parent = cbl_field_of(e);
706 if( parent->level == field->level || field->level == 66) {
707 return parent;
708 }
709 return NULL;
710 }
711 return NULL;
712 }
713
714 static cbl_field_t *
715 symbol_explicitly_redefines( const cbl_field_t *field ) {
716 auto f = symbol_redefines(field);
717 if( f && is_record_area(f) ) return NULL;
718 return f;
719 }
720
721 static uint32_t
722 field_size( const struct cbl_field_t *field ) {
723 size_t n = field->occurs.ntimes();
724 return field->data.capacity * (n > 0? n : 1);
725 }
726
727 const char *
728 cbl_field_attr_str( cbl_field_attr_t attr ) {
729 switch(attr) {
730 case none_e: return "none";
731 case figconst_1_e: return "figconst_1";
732 case figconst_2_e: return "figconst_2";
733 case figconst_4_e: return "figconst_4";
734 case rjust_e: return "rjust";
735 case ljust_e: return "ljust";
736 case zeros_e: return "zeros";
737 case signable_e: return "signable";
738 case constant_e: return "constant";
739 case function_e: return "function";
740 case quoted_e: return "quoted";
741 case filler_e: return "filler";
742 case _spare_e: return "temporary";
743 case intermediate_e: return "intermediate";
744 case embiggened_e: return "embiggened";
745 case all_alpha_e: return "all_alpha";
746 case all_x_e: return "all_x";
747 case all_ax_e: return "all_ax";
748 case prog_ptr_e: return "prog_ptr";
749 case scaled_e: return "scaled";
750 case refmod_e: return "refmod";
751 case based_e: return "based";
752 case any_length_e: return "any_length";
753 case global_e: return "global";
754 case external_e: return "external";
755 case blank_zero_e: return "blank_zero";
756 case linkage_e: return "linkage";
757 case local_e: return "local";
758 case leading_e: return "leading";
759 case separate_e: return "separate";
760 case envar_e: return "envar";
761 case dnu_1_e: return "dnu_1";
762 case bool_encoded_e: return "bool";
763 case hex_encoded_e: return "hex";
764 case depends_on_e: return "depends_on";
765 case initialized_e: return "initialized";
766 case has_value_e: return "has_value";
767 case ieeedec_e: return "ieeedec";
768 case big_endian_e: return "big";
769 case same_as_e: return "same_as";
770 case record_key_e: return "record_key";
771 case typedef_e: return "typedef";
772 case strongdef_e: return "strongdef";
773 }
774 return "???";
775 }
776
777 uint32_t
778 cbl_field_t::size() const {
779 return field_size(this);
780 }
781
782 uint64_t
783 cbl_field_t::set_attr( cbl_field_attr_t attr ) {
784 if( attr == signable_e ) {
785 if( ! has_attr(attr) && this->var_decl_node != NULL ) {
786 parser_field_attr_set(this, attr);
787 }
788 }
789 return this->attr |= uint64_t(attr);
790 }
791
792 uint64_t
793 cbl_field_t::clear_attr( cbl_field_attr_t attr ) {
794 if( attr == signable_e ) {
795 if( this->var_decl_node != nullptr && has_attr(attr) ) {
796 parser_field_attr_set(this, attr, false);
797 }
798 }
799 return this->attr &= ~uint64_t(attr);
800 }
801
802 static uint32_t
803 field_memsize( const struct cbl_field_t *field ) {
804 uint32_t n = field->occurs.ntimes();
805 n = field->data.capacity * (n > 0? n : 1);
806 return std::max(n, field->data.memsize);
807 }
808
809 static inline bool
810 field_skippable( const struct cbl_field_t *field ) {
811 // skip forward references
812 if( field->type == FldForward ) {
813 return true;
814 }
815
816 // typedef takes no space
817 if( field->is_typedef() ) {
818 return true;
819 }
820
821 // skip 88s and 66s because they don't add to capacity
822 if( field->level == 66 || field->level == 88 ) {
823 return true;
824 }
825
826 // skip switch values because they're just compile-time constants
827 if( field->type == FldSwitch ) {
828 return true;
829 }
830
831 // skip INDEXED BY if its level is 0.
832 if( field->level == 0 && field->type == FldIndex ) {
833 return true;
834 }
835 return false;
836 }
837
838 /*
839 * Start at a LEVEL01 field and walk through it until the next LEVEL01
840 * or LEVEL77, if any. Update the offset of each subfield field
841 * based on the sizes of all the preceding items.
842 *
843 * A field whose parent is the same level is a REDEFINE. It does not
844 * use additional storage, and has an offset the same as its "parent".
845 */
846 static struct symbol_elem_t *
847 update_block_offsets( struct symbol_elem_t *block)
848 {
849 assert(block);
850 assert(block->type == SymField);
851
852 uint32_t offset = cbl_field_of(block)->offset;
853 const uint32_t block_level = cbl_field_of(block)->level;
854
855 struct symbol_elem_t *e = block;
856 for( ++e; e < symbols_end(); e++ ) {
857 if( e->type != SymField ) {
858 // Ignore non-fields
859 continue;
860 }
861
862 cbl_field_t *field = cbl_field_of(e);
863
864 if( field->level == 66 ) {
865 field->offset = parent_of(field)->offset;
866 continue;
867 }
868
869 if( field_skippable(field) ) {
870 continue;
871 }
872
873 if( field->level <= block_level || field->level == LEVEL77 ) {
874 break; // end of group
875 }
876
877 if( symbol_redefines(field) ) {
878 field->offset = parent_of(field)->offset;
879 } else {
880 field->offset = offset;
881 offset += field_memsize(field);
882 }
883
884 if( field->type == FldGroup ) {
885 e = update_block_offsets(e) - 1;
886 }
887 }
888 return e;
889 }
890
891 static inline bool
892 end_of_group( const cbl_field_t *group, const cbl_field_t *field ) {
893 // A group ends when we strike a level less than or equal to
894 // group_symbol->level, or when we hit a LEVEL77.
895
896 // reject forward fields
897 if( is_forward(field) ) return false;
898
899 // If field redefines group, we're not at the end.
900 if( group == symbol_redefines(field) ) return false;
901
902 // An index that is part of a table is part of the group.
903 if( field->level == 0 && field->type == FldIndex ) return false;
904
905 return
906 field->level <= group->level ||
907 field->level == LEVEL77 ||
908 field->level == 66;
909 }
910
911 class eog_t {
912 const cbl_field_t * group;
913 public:
914 explicit eog_t( const symbol_elem_t *e ) : group(cbl_field_of(e)) {}
915
916 bool operator()( symbol_elem_t& e ) {
917 return e.type == SymField && end_of_group(group, cbl_field_of(&e));
918 }
919 };
920
921 size_t
922 end_of_group( size_t igroup ) {
923 symbol_elem_t * group(symbol_at(igroup));
924
925 if( group->type == SymFile ) {
926 cbl_field_t * first_record = symbol_file_record(cbl_file_of(group));
927 assert(first_record);
928 group = symbol_at(field_index(first_record));
929 for( auto e = group + 1; e < symbols_end(); e++ ) {
930 auto isym = symbol_index(e);
931 if( e->program != group->program ) return isym;
932 if( e->type == SymLabel ) return isym; // end of data division
933 if( e->type == SymField ) {
934 const cbl_field_t * f = cbl_field_of(e);
935 if( f->level == LEVEL77 || f->level == 66 ) return isym;
936 if( f->level == 1 && f->parent != igroup ) {
937 return isym;
938 }
939 }
940 }
941 return symbols.nelem;
942 }
943
944 eog_t eog(symbol_at(igroup));
945 const symbol_elem_t *e = std::find_if( symbols_begin(++igroup), symbols_end(), eog );
946 return e - symbols_begin();
947 }
948
949 size_t
950 symbol_field_capacity( const cbl_field_t *field ) {
951 class sym_field_size {
952 public:
953 sym_field_size() {}
954 static size_t capacity( size_t n, const symbol_elem_t& elem ) {
955 if( elem.type == SymField ) {
956 const cbl_field_t *f = cbl_field_of(&elem);
957 if( is_elementary(f->type) ) {
958 return n + ::field_size(f);
959 }
960 }
961 return n;
962 }
963 };
964 size_t bog = field_index(const_cast<cbl_field_t*>(field));
965 size_t eog = end_of_group(bog);
966 size_t size = std::accumulate( symbol_at(bog), symbol_at_impl(eog),
967 0, sym_field_size::capacity );
968
969 if(true) dbgmsg("%s: %02u %s.data.capacity was computed as " HOST_SIZE_T_PRINT_UNSIGNED,
970 __func__, field->level, field->name, (fmt_size_t)size);
971
972 return size;
973 }
974
975 static bool
976 has_odo( const symbol_elem_t& e ) {
977 return e.type == SymField && cbl_field_of(&e)->occurs.depending_on > 0;
978 }
979
980 // a debug version of symbol_find_odo
981 struct cbl_field_t *
982 symbol_find_odo_debug( cbl_field_t * field ) {
983 size_t bog = field_index(field), eog = end_of_group(bog);
984 dbgmsg("%s: %s is #" HOST_SIZE_T_PRINT_UNSIGNED " - #" HOST_SIZE_T_PRINT_UNSIGNED
985 " of " HOST_SIZE_T_PRINT_UNSIGNED ", ends at %s", __func__,
986 field->name, (fmt_size_t)bog, (fmt_size_t)eog, (fmt_size_t)symbols.nelem,
987 eog == symbols.nelem? "[end]" : cbl_field_of(symbol_at(eog))->name );
988
989 auto e = std::find_if( symbol_at(bog), symbol_at_impl(eog, true), has_odo );
990 if( e != symbol_at_impl(eog, true) ) {
991 dbgmsg("%s: %s has ODO at #" HOST_SIZE_T_PRINT_UNSIGNED " (return '%s')", __func__,
992 field->name, (fmt_size_t)symbol_index(e),
993 cbl_field_of(e)->name );
994 }
995 return e == symbol_at_impl(eog, true)? NULL : cbl_field_of(e);
996 }
997
998 // Return OCCURS DEPENDING ON table subordinate to field, if any.
999 struct cbl_field_t *
1000 symbol_find_odo( const cbl_field_t * field ) {
1001 size_t bog = field_index(field), eog = end_of_group(bog);
1002 auto e = std::find_if( symbol_at(bog), symbol_at_impl(eog, true), has_odo );
1003 return e == symbol_at_impl(eog, true)? NULL : cbl_field_of(e);
1004 }
1005
1006 static inline bool
1007 is_index( const cbl_field_type_t type ) { return type == FldIndex; }
1008
1009 static size_t
1010 symbols_dump( size_t first, bool header ) {
1011 size_t ninvalid = 0;
1012
1013 if( !yydebug ) return 0;
1014
1015 if( header ) {
1016 fprintf(stderr, "Symbol Table has " HOST_SIZE_T_PRINT_UNSIGNED " elements\n",
1017 (fmt_size_t)(symbols_end() - symbols_begin()));
1018 }
1019
1020 for( struct symbol_elem_t *e = symbols_begin(first); e < symbols_end(); e++ ) {
1021 char *s;
1022
1023 switch(e->type) {
1024 case SymFilename:
1025 s = xasprintf("%4" GCC_PRISZ "u %-18s %s", (fmt_size_t)e->program,
1026 "Filename", e->elem.filename);
1027 break;
1028 case SymDataSection:
1029 s = xasprintf("%4" GCC_PRISZ "u %-18s line %d", (fmt_size_t)e->program,
1030 cbl_section_of(e)->name(), cbl_section_of(e)->line);
1031 break;
1032 case SymField: {
1033 auto field = cbl_field_of(e);
1034 char *odo_str = NULL;
1035 if( field->occurs.depending_on != 0 ) {
1036 odo_str = xasprintf("odo " HOST_SIZE_T_PRINT_UNSIGNED,
1037 (fmt_size_t)field->occurs.depending_on );
1038 }
1039 ninvalid += cbl_field_of(e)->type == FldInvalid? 1 : 0;
1040 s = xasprintf("%4" GCC_PRISZ "u %-18s %s (%s)", (fmt_size_t)e->program,
1041 cbl_field_type_str(cbl_field_of(e)->type) + 3,
1042 field_str(cbl_field_of(e)),
1043 odo_str? odo_str :
1044 cbl_field_type_str(cbl_field_of(e)->usage) + 3);
1045 }
1046 break;
1047 case SymLabel:
1048 s = xasprintf("%4" GCC_PRISZ "u %-18s %s", (fmt_size_t)e->program,
1049 "Labe1l", e->elem.label.str());
1050 if( LblProgram == cbl_label_of(e)->type ) {
1051 const auto& L = *cbl_label_of(e);
1052 if( L.os_name ) {
1053 char *base = s;
1054 s = xasprintf("%s as \"%s\")", base, L.os_name);
1055 free(base);
1056 }
1057 }
1058 break;
1059 case SymSpecial:
1060 s = xasprintf("%4" GCC_PRISZ "u %-18s id=%2d, %s", (fmt_size_t)e->program,
1061 "Special", e->elem.special.id, e->elem.special.name);
1062 break;
1063 case SymAlphabet:
1064 s = xasprintf("%4" GCC_PRISZ "u %-18s encoding=%2d, '%s'",
1065 (fmt_size_t)e->program, "Alphabet",
1066 int(e->elem.alphabet.encoding), e->elem.alphabet.name);
1067 break;
1068 case SymFile:
1069 s = xasprintf("%4" GCC_PRISZ "u %-18s %-20s", (fmt_size_t)e->program,
1070 "File", e->elem.file.name);
1071 {
1072 char same_as[26] = "";
1073 if( cbl_file_of(e)->same_record_as > 0 ) {
1074 sprintf(same_as, "s%3" GCC_PRISZ "u",
1075 (fmt_size_t)cbl_file_of(e)->same_record_as);
1076 }
1077 const char *type = file_org_str(e->elem.file.org);
1078 char *part = s;
1079
1080 s = xasprintf("%s %-4s %s %s %s{" HOST_SIZE_T_PRINT_UNSIGNED "-"
1081 HOST_SIZE_T_PRINT_UNSIGNED "} status=#"
1082 HOST_SIZE_T_PRINT_UNSIGNED,
1083 part, same_as, type,
1084 e->elem.file.keys_str(),
1085 cbl_file_of(e)->varies()? "varies " : "",
1086 (fmt_size_t)cbl_file_of(e)->varying_size.min,
1087 (fmt_size_t)cbl_file_of(e)->varying_size.max,
1088 (fmt_size_t)cbl_file_of(e)->user_status);
1089 free(part);
1090 }
1091 break;
1092 default:
1093 dbgmsg("%s: cannot dump symbol type %d", __func__, e->type);
1094 continue;
1095 }
1096 fprintf(stderr, "%4" GCC_PRISZ "u: %s\n",
1097 (fmt_size_t)(e - symbols_begin()), s);
1098 free(s);
1099 }
1100 return ninvalid;
1101 }
1102
1103 static bool
1104 grow_redefined_group( cbl_field_t *redefined, const cbl_field_t *field ) {
1105 assert(redefined);
1106 assert(field);
1107 assert(redefined == symbol_redefines(field));
1108
1109 /*
1110 * When this function is called, redefined elementary items are
1111 * already resized, if eligible.
1112 */
1113 if( redefined->type != FldGroup ) return false;
1114
1115 /*
1116 * 8) The storage area required for the subject of the entry
1117 * shall not be larger than the storage area required for the
1118 * data item referenced by data-name-2, unless the data item
1119 * referenced by data- name-2 has been specified with level
1120 * number 1 and without the EXTERNAL clause.
1121 */
1122 if( 1 < redefined->level ) {
1123 if( field_memsize(redefined) < field_memsize(field) ) {
1124 ERROR_FIELD(field, "line %d: %s (size %u) larger than REDEFINES %s (size %u)",
1125 field->line,
1126 field->name, field_memsize(field),
1127 redefined->name, field_memsize(redefined));
1128 return false;
1129 }
1130 }
1131
1132 redefined->data.memsize = std::max(field_memsize(redefined),
1133 field_memsize(field));
1134
1135 return true;
1136 }
1137
1138
1139 /*
1140 * Input is a symbol-table element, always a field.
1141 * For elementary fields, return the input.
1142 * For groups, return the element after the last field in the group.
1143 */
1144 static struct symbol_elem_t *
1145 calculate_capacity( struct symbol_elem_t *e) {
1146 // For each group, sum capacities of children. Exclude:
1147 // FldClass, FldForward
1148 // FldIndex with level 0 (really, any level 0)
1149 // REDEFINES
1150
1151 cbl_field_t *group = cbl_field_of(e);
1152
1153 if( is_literal(group) ) return e;
1154 if( is_index(group->type) ) return e; // 01 can be index type.
1155
1156 if( is_elementary(group->type) ) { // "group" is in fact just a field
1157 if( is_record_area(group) ) {
1158 if( group->data.capacity == 0 ) {
1159 const auto& file = *cbl_file_of(symbol_at(group->file));
1160 group->data.capacity = file.varying_size.max;
1161 }
1162
1163 // Find 01s for the file that is not a record area field.
1164 for( auto p = symbols_begin(e->program) + 1; p < symbols_end(); ++p ) {
1165 p = std::find_if( p, symbols_end(),
1166 [group](const symbol_elem_t& elem) {
1167 if( elem.type == SymField ) {
1168 auto field = cbl_field_of(&elem);
1169 return field != group &&
1170 field->file == group->file;
1171 }
1172 return false;
1173 } );
1174 // If an 01 record exists for the FD/SD, use its capacity as the
1175 // default_record capacity.
1176 if( p != symbols_end() ) {
1177 const cbl_field_t * record = cbl_field_of(p);
1178 assert(record->level == 1);
1179 e = calculate_capacity(p);
1180 auto record_size = std::max(record->data.memsize,
1181 record->data.capacity);
1182 group->data.capacity = std::max(group->data.capacity, record_size);
1183 }
1184 }
1185
1186 // SAME AREA AS causes this record area to redefine another.
1187 // Reach back to that symbol to set its capacity, if need be.
1188 auto area = symbol_redefines(group);
1189 if( area ) {
1190 area->data.capacity = std::max(area->data.capacity,
1191 group->data.capacity);
1192 }
1193
1194 return e; // no 01, return self
1195 }
1196
1197 cbl_field_t *redefined = symbol_redefines(group);
1198
1199 if( redefined ) {
1200 redefined->data.memsize = std::max(field_memsize(redefined), field_size(group));
1201 if( redefined->data.memsize == redefined->data.capacity ) {
1202 redefined->data.memsize = 0;
1203 }
1204 }
1205 return e;
1206 }
1207
1208 if(yydebug && group->type != FldGroup) {
1209 dbgmsg("Field #" HOST_SIZE_T_PRINT_UNSIGNED " '%s' is not a group",
1210 (fmt_size_t)symbol_index(e), group->name);
1211 symbols_dump(symbols.first_program, true);
1212 }
1213 if( group->type == FldInvalid ) return e;
1214
1215 assert(group->type == FldGroup);
1216
1217 group->data.capacity = 0;
1218
1219 std::list<cbl_field_t*> members;
1220
1221 while( ++e < symbols_end() ) {
1222 if( e->type != SymField ) continue;
1223 cbl_field_t *field = cbl_field_of(e);
1224
1225 if( field_skippable(field) ) continue;
1226
1227 // Stop if field isn't a member of the group.
1228 if( end_of_group(group, field) ) break;
1229
1230 if( field->type == FldGroup ) {
1231 e = calculate_capacity(e);
1232 e--; // set e to last symbol processed (not next one, because ++e)
1233 }
1234
1235 members.push_back(field);
1236 }
1237
1238 // Print accumulating details for one group to debug log.
1239 bool details = false;
1240
1241 // At end of group, members is a list of all immediate children, any
1242 // of which might have been redefined and so acquired a memsize.
1243 // Any element of members that redefines something redefines group.
1244 uint32_t max_memsize = 0;
1245 for( auto field : members ) {
1246 cbl_field_t *redefined = symbol_redefines(field);
1247 if( redefined ) {
1248 if( group != redefined ) {
1249 grow_redefined_group(redefined, field);
1250 }
1251 max_memsize = std::max(max_memsize, field_memsize(field));
1252
1253 field->data.memsize = 0;
1254
1255 if( redefined->data.memsize == redefined->data.capacity ) {
1256 redefined->data.memsize = 0;
1257 }
1258 continue;
1259 }
1260 group->data.capacity += field_size(field);
1261 group->data.memsize += field_memsize(field);
1262
1263 // If group has a parent that is a record area, expand it, too.
1264 if( 0 < group->parent ) {
1265 redefined = symbol_redefines(group);
1266 if( redefined && is_record_area(redefined) ) {
1267 if( redefined->data.capacity < group->data.memsize ) {
1268 redefined->data.capacity = group->data.memsize;
1269 }
1270 }
1271 }
1272
1273 if( details ) {
1274 dbgmsg("%s:%d: %s", __func__, __LINE__, field_str(field) );
1275 dbgmsg("%s:%d: %s", __func__, __LINE__, field_str(group) );
1276 }
1277 }
1278
1279 group->data.memsize = std::max(max_memsize, group->data.memsize);
1280 if( group->data.memsize == group->data.capacity ) group->data.memsize = 0;
1281
1282 if( 0 < group->data.memsize && group->data.memsize < group->data.capacity ) {
1283 if( yydebug ) {
1284 dbgmsg( "%s:%d: small capacity?\n\t%s", __func__, __LINE__, field_str(group) );
1285 }
1286 group->data.memsize = group->data.capacity;
1287 }
1288
1289 if( group->data.capacity == 0 ) {
1290 dbgmsg( "%s:%d: zero capacity?\n\t%s", __func__, __LINE__, field_str(group) );
1291 }
1292
1293 switch( group->level ) {
1294 case 1: case 77:
1295 if( dialect_mf() && is_table(group) ) {
1296 size_t elem_size = std::max(group->data.memsize, group->data.memsize);
1297 group->data.memsize = elem_size * group->occurs.ntimes();
1298 }
1299 }
1300 return e;
1301 }
1302
1303 static void
1304 verify_block( const struct symbol_elem_t *block,
1305 const struct symbol_elem_t *eoblock )
1306 {
1307 for( const struct symbol_elem_t *e=block; e < eoblock; e++ ) {
1308 if( e->type != SymField ) {
1309 continue;
1310 }
1311 }
1312 }
1313
1314 static symbol_type_t
1315 parent_type( const cbl_field_t *f ) {
1316 return f->parent == 0? (symbol_type_t)-1 : symbol_at(f->parent)->type;
1317 }
1318
1319 cbl_field_t *
1320 parent_of( const cbl_field_t *f ) {
1321 return SymField == parent_type(f) ? cbl_field_of(symbol_at(f->parent)) : NULL;
1322 }
1323
1324 const cbl_field_t *
1325 occurs_in( const cbl_field_t *f ) {
1326 while( (f = parent_of(f)) != NULL ) {
1327 if( f->occurs.ntimes() > 0 ) break;
1328 }
1329 return f;
1330 }
1331
1332 bool
1333 immediately_follows( const cbl_field_t *field ) {
1334 auto esym = symbols_end();
1335 auto e = std::find_if( symbol_at(field_index(field)) + 1, esym,
1336 []( auto& e ) {
1337 if( e.type != SymField ) return false;
1338 auto f = cbl_field_of(&e);
1339 return f->level == 1;
1340 } );
1341 return e == esym;
1342 }
1343
1344 bool
1345 is_variable_length( const cbl_field_t *field ) {
1346 // RENAMES may be included in end_of_group.
1347 size_t isym = field_index(field), esym = end_of_group(isym);
1348 bool odo = std::any_of( symbol_at(isym) + 1, symbol_at_impl(esym),
1349 [field]( const auto& elem ) {
1350 if( elem.type == SymField ) {
1351 auto f = cbl_field_of(&elem);
1352 if( field->level < f->level ) { // exclude RENAMES
1353 return 0 < f->occurs.depending_on;
1354 }
1355 }
1356 return false;
1357 } );
1358 return odo;
1359 }
1360
1361 /*
1362 * "None of the items within the range, including data-name-2 and
1363 * data-name-3, if specified, shall be of class object, message-tag,
1364 * or pointer, a strongly-typed group item, an item subordinate to a
1365 * strongly- typed group item, a variable-length data item, or an
1366 * occurs-depending table."
1367 */
1368 cbl_field_t *
1369 rename_not_ok( const cbl_field_t *first, const cbl_field_t *last) {
1370 symbol_elem_t
1371 *beg = symbol_at(field_index(first)),
1372 *end = symbol_at(field_index(last));
1373 auto e = std::find_if( beg, ++end,
1374 []( auto& e ) {
1375 if( e.type != SymField ) return false;
1376 auto f = cbl_field_of(&e);
1377 switch( f->type ) {
1378 case FldPointer:
1379 return true;
1380 default:
1381 break;
1382 }
1383 if( f->occurs.depending_on ) return true;
1384 return false;
1385 } );
1386 return e == end? NULL : cbl_field_of(e);
1387 }
1388
1389 cbl_file_t *
1390 symbol_record_file( const cbl_field_t *f ) {
1391 do {
1392 if( is_record_area(f) ) return cbl_file_of(symbol_at(f->parent));
1393 if( f->file ) return cbl_file_of(symbol_at(f->file));
1394 } while( (f = parent_of(f)) != NULL );
1395 return NULL;
1396 }
1397
1398 size_t
1399 dimensions( const cbl_field_t *f ) {
1400 size_t n = is_table(f)? 1 : 0;
1401
1402 if( f->type == FldIndex ) return 0;
1403
1404 while( (f = parent_of(f)) != NULL ) {
1405 if( is_table(f) ) n++;
1406 }
1407
1408 return n;
1409 }
1410
1411 const char *
1412 cbl_figconst_str( cbl_figconst_t fig ) {
1413 switch(fig) {
1414 case normal_value_e: return "NORMAL CONSTANT";
1415 case low_value_e: return "LOW-VALUES";
1416 case zero_value_e: return "ZEROS";
1417 case space_value_e: return "SPACES";
1418 case quote_value_e: return "QUOTES";
1419 case null_value_e: return "NULLS";
1420 case high_value_e: return "HIGH-VALUES";
1421 }
1422 return "NOT FIGURATIVE CONSTANT";
1423 }
1424
1425 static const char *
1426 value_or_figconst_name( const char *value ) {
1427 auto fig = cbl_figconst_of(value);
1428 return normal_value_e == fig? value : cbl_figconst_str(fig);
1429 }
1430
1431 const char *
1432 cbl_field_t::attr_str( const std::vector<cbl_field_attr_t>& attrs ) const
1433 {
1434 const char *sep = "";
1435 char *out = NULL;
1436
1437 for( auto attr_l : attrs ) {
1438 char *part = out;
1439 if( has_attr(attr_l) ) {
1440 int erc = asprintf(&out, "%s%s%s",
1441 part? part : "", sep, cbl_field_attr_str(attr_l));
1442 if( -1 == erc ) return part;
1443 free(part);
1444 sep = ", ";
1445 }
1446 }
1447 return out? out : "none";
1448 }
1449
1450 char *
1451 field_str( const cbl_field_t *field ) {
1452 static char string[3*sizeof(cbl_name_t)];
1453 char *pend = string;
1454
1455 char name[2*sizeof(cbl_name_t)] = "";
1456 if( true ) {
1457 if( field->occurs.ntimes() == 0 ) {
1458 snprintf(name, sizeof(name), "%s", field->name);
1459 } else {
1460 std::vector <char> updown(1 + field->occurs.nkey, '\0');
1461 for( size_t i=0; i < field->occurs.nkey; i++ ) {
1462 updown[i] = field->occurs.keys[i].ascending? 'A' : 'D';
1463 }
1464 snprintf(name, sizeof(name), "%s[" HOST_SIZE_T_PRINT_UNSIGNED "]%s",
1465 field->name, (fmt_size_t)field->occurs.ntimes(), updown.data());
1466 }
1467 }
1468
1469 pend += snprintf(pend, string + sizeof(string) - pend,
1470 "%02u %-20s ", field->level, name);
1471
1472 char offset[32] = "";
1473 if( field->level > 1 ) {
1474 sprintf( offset, "off%3" GCC_PRISZ "u", (fmt_size_t)field->offset );
1475 }
1476
1477 char parredef =
1478 parent_of(field) != NULL && parent_of(field)->level == field->level? 'r' : 'P';
1479 if( 'r' == parredef && field->level == 0 ) parredef = 'p';
1480 if( field->has_attr(typedef_e) ) parredef = 'T';
1481
1482 const char *data = field->data.initial? field->data.initial : NULL;
1483 if( data ) {
1484 auto fig = cbl_figconst_of(data);
1485 if( normal_value_e != fig ) {
1486 data = cbl_figconst_str(fig);
1487 } else {
1488 char *s;
1489 auto n = asprintf(&s, "'%s'", data);
1490 gcc_assert(n);
1491 auto eodata = data + field->data.capacity;
1492 // It is possible for data.initial to be shorter than capacity.
1493
1494 // This whole thing needs to be reexamined. There is an assumption for
1495 // FldAlphanumeric values that the valid data in data.initial be the same
1496 // length as data.capacity. But that does not hold true for other types.
1497 // For example, a PIC 9V9 has a capacity of two, but the initial
1498 // string provided by the COBOL programmer might be "1.2". Likewise, a
1499 // PIC 999999 (capacity 5) might have a value of "1".
1500
1501 for(size_t i = 0; i<field->data.capacity; i++)
1502 {
1503 if( data[i] == '\0' )
1504 {
1505 eodata = data + i;
1506 break;
1507 }
1508 }
1509 if( eodata != std::find_if_not(data, eodata, fisprint) ) {
1510 char *p = reinterpret_cast<char*>(xrealloc(s, n + 8 + 2 * field->data.capacity));
1511 if( is_elementary(field->type) &&
1512 field->type != FldPointer && p != NULL ) {
1513 s = p;
1514 p += n;
1515 strcat( p, "(0x" );
1516 p += 3;
1517 for( auto d=data; d < eodata; d++ ) {
1518 p += sprintf(p, "%02x", *d);
1519 }
1520 strcat( p++, ")" );
1521 }
1522 }
1523 data = s;
1524 }
1525 } else {
1526 data = "NULL";
1527 if( field->type == FldSwitch ) {
1528 data = xasprintf("0x%02x", field->data.upsi_mask_of()->value);
1529 }
1530 }
1531 if( field->level == 88 ) {
1532 const auto& dom = *field->data.domain_of();
1533 data = xasprintf("%s%s %s - %s%s",
1534 dom.first.all? "A" : "",
1535 value_or_figconst_name(dom.first.name()) ,
1536 dom.first.is_numeric? "(num)" : "",
1537 dom.last.all? "A" : "",
1538 dom.last.name()? value_or_figconst_name(dom.last.name()) : "");
1539 }
1540
1541 char storage_type = 0x20;
1542 assert( (field->attr & (linkage_e | local_e)) < (linkage_e | local_e) );
1543 if( field->attr & linkage_e ) storage_type = 'L';
1544 if( field->attr & local_e ) storage_type = 'w'; // because 'l' hard to read
1545
1546 static const std::vector<cbl_field_attr_t> attrs {
1547 figconst_1_e, figconst_2_e, figconst_4_e, rjust_e, ljust_e,
1548 zeros_e, signable_e, constant_e, function_e, quoted_e, filler_e,
1549 intermediate_e, embiggened_e, all_alpha_e, all_x_e,
1550 all_ax_e, prog_ptr_e, scaled_e, refmod_e, based_e, any_length_e,
1551 /* global_e, external_e, */ blank_zero_e, /* linkage_e, local_e, */ leading_e,
1552 separate_e, envar_e, dnu_1_e, bool_encoded_e, hex_encoded_e,
1553 depends_on_e, /* initialized_e, */ has_value_e, ieeedec_e, big_endian_e,
1554 same_as_e, record_key_e, typedef_e, strongdef_e,
1555 };
1556
1557 pend += snprintf(pend, string + sizeof(string) - pend,
1558 "%c%3" GCC_PRISZ "u %-6s %c%c%c %2u{%3u,%u,%d = %s} (%s), line %d",
1559 parredef, (fmt_size_t)field->parent, offset,
1560 (field->attr & global_e)? 'G' : 0x20,
1561 (field->attr & external_e)? 'E' : 0x20,
1562 storage_type,
1563 field->data.memsize,
1564 field->data.capacity, field->data.digits, field->data.rdigits,
1565 data, field->attr_str(attrs), field->line );
1566 return string;
1567 }
1568
1569 void
1570 labels_dump() {
1571 symbols_dump( symbols.procedures, true );
1572 }
1573
1574 struct capacity_of {
1575 uint32_t capacity;
1576
1577 capacity_of() : capacity(0) {}
1578
1579 capacity_of operator()( symbol_elem_t& elem ) {
1580 if( elem.type == SymField ) {
1581 const cbl_field_t *f = cbl_field_of(&elem);
1582 if( is_elementary(f->type) ) {
1583 capacity += field_size(f);
1584 }
1585 }
1586 return *this;
1587 }
1588 };
1589
1590 static void
1591 extend_66_capacity( cbl_field_t *alias ) {
1592 static_assert(sizeof(symbol_elem_t*) == sizeof(const char *),
1593 "all pointers must be same size");
1594 assert(alias->data.picture);
1595 assert(alias->type == FldGroup);
1596 symbol_elem_t *e = symbol_at(alias->parent);
1597 symbol_elem_t *e2 =
1598 reinterpret_cast<symbol_elem_t*>(const_cast<char*>(alias->data.picture));
1599 assert(e < e2);
1600 alias->data.picture = NULL;
1601
1602 capacity_of cap;
1603 if( alias->type == FldGroup ) {
1604 e2 = symbol_at_impl(end_of_group(symbol_index(e2)));
1605 } else {
1606 ++e2;
1607 }
1608 alias->data.capacity = std::for_each(e, e2, cap).capacity;
1609 assert(alias->data.capacity > 0);
1610 }
1611
1612 bool
1613 symbols_alphabet_set( size_t program, const char name[]) {
1614 struct alpha {
1615 void operator()( symbol_elem_t& elem ) const {
1616 if( elem.type == SymAlphabet ) {
1617 parser_alphabet( *cbl_alphabet_of(&elem) );
1618 }
1619 }
1620 };
1621
1622 // Define alphabets for codegen.
1623 std::for_each(symbols_begin(), symbols_end(), alpha() );
1624
1625 // Set collation sequence before parser_symbol_add.
1626 if( name ) {
1627 symbol_elem_t *e = symbol_alphabet(program, name);
1628 if( !e ) {
1629 return false;
1630 }
1631 parser_alphabet_use(*cbl_alphabet_of(e));
1632 }
1633 return true;
1634 }
1635
1636 static std::ostream&
1637 operator<<( std::ostream& os, const cbl_occurs_bounds_t& bound ) {
1638 return os << bound.lower << ',' << bound.upper;
1639 }
1640
1641 #pragma GCC diagnostic push
1642 #pragma GCC diagnostic ignored "-Wunused-function"
1643 // Keep this debugging function around for when it is needed
1644 static std::ostream&
1645 operator<<( std::ostream& os, const cbl_field_data_t& field ) {
1646 return os << field.memsize << ','
1647 << field.capacity << ','
1648 << field.digits << ','
1649 << field.rdigits << ','
1650 << (field.picture? field.picture : "");
1651 }
1652
1653 static std::ostream&
1654 operator<<( std::ostream& os, const cbl_field_t& field ) {
1655 return os << field.parent
1656 << ',' << field.level
1657 << ',' << field.name
1658 << ',' << field.offset
1659 << ',' << cbl_field_type_str(field.type)
1660 << ',' << "0x" << std::hex << field.attr << std::dec
1661 // occurs
1662 << ',' << field.occurs.depending_on
1663 << ',' << field.occurs.bounds
1664 << ',' << field.line
1665 << ',' << field.data;
1666 }
1667 #pragma GCC diagnostic pop
1668
1669 static std::map<size_t, std::set<size_t>> same_record_areas;
1670 size_t parse_error_count();
1671
1672 /*
1673 * This function produces a zero-filled level number, so 1 becomes "01". It's
1674 * needed because the diagnostic format string doesn't support zero-filled
1675 * integer conversion or width.
1676 */
1677 const char *
1678 cbl_field_t::level_str( uint32_t level ) {
1679 char *str = xasprintf( "%02u", level );
1680 return str;
1681 }
1682
1683 size_t
1684 symbols_update( size_t first, bool parsed_ok ) {
1685 struct symbol_elem_t *p, *pend;
1686 std::list<cbl_field_t*> shared_record_areas;
1687
1688 for( p = symbols_begin(first); p < symbols_end(); p++ ) {
1689
1690 if( p->type == SymAlphabet ) continue; // Alphabets already processed.
1691 if( p->type == SymFile ) continue; // Do fields before files.
1692 if( p->type != SymField ) continue;
1693
1694 cbl_field_t *field = cbl_field_of(p);
1695 if( field->our_index == 0 ) field->our_index = symbol_index(p);
1696 if( field->type == FldForward ) continue;
1697 if( field->type == FldSwitch ) continue;
1698 if( is_literal(field) && field->var_decl_node != NULL ) continue;
1699
1700 switch(field->level) {
1701 case 0:
1702 if( field->is_key_name() ) {
1703 update_symbol_map2(p);
1704 continue;
1705 }
1706 break;
1707 case 1:
1708 pend = calculate_capacity(p);
1709 if( dialect_mf() && is_table(field) ) {
1710 if( field->data.memsize < field->size() ) {
1711 field->data.memsize = field->size();
1712 }
1713 }
1714 update_block_offsets(p);
1715 verify_block(p, pend);
1716 break;
1717 case 66:
1718 assert(field->parent > 0);
1719 assert(symbol_at(field->parent)->type == SymField);
1720 if( field->type == FldGroup && field->data.picture ) {
1721 extend_66_capacity(field);
1722 } else {
1723 auto data = parent_of(field)->data;
1724 data.memsize = 0;
1725 field->data = data;
1726 }
1727 break;
1728 // no special processing for other levels
1729 }
1730
1731 // Update ODO field in situ.
1732 if( is_table(field) ) {
1733 size_t& odo = field->occurs.depending_on;
1734 if( odo != 0 ) {
1735 auto odo_field = cbl_field_of(symbol_at(odo)); // get not-FldForward if exists
1736 if( is_forward(odo_field) ) {
1737 ERROR_FIELD(field, "table %s (line %d) DEPENDS ON %s, which is not defined",
1738 field->name, field->line, odo_field->name);
1739 } else {
1740 // set odo to found field
1741 odo = field_index(odo_field);
1742 }
1743 }
1744 }
1745
1746 bool size_invalid = field->data.memsize > 0 && symbol_redefines(field);
1747 if( size_invalid ) { // redefine of record area is ok
1748 const cbl_field_t * redefined = symbol_redefines(field);
1749 size_invalid = ! is_record_area(redefined);
1750 }
1751 if( !field->is_valid() || size_invalid )
1752 {
1753 size_t isym = p - symbols_begin();
1754 symbols_dump(symbols.first_program, true);
1755 if( symbol_at(field->parent)->type == SymFile ) {
1756 assert(field->parent == field_index(field) + 1);
1757 auto e = std::find_if( symbols_begin(field->parent), symbols_end(),
1758 [program = p->program, ifile = field->parent]
1759 ( const auto& elem ) {
1760 if( elem.program == program ) {
1761 if( elem.type == SymField ) {
1762 auto f = cbl_field_of(&elem);
1763 return f->parent == ifile;
1764 }
1765 }
1766 return false;
1767 } );
1768 if( e == symbols_end() ) {
1769 // no field redefines the file's default record
1770 auto file = cbl_file_of(symbol_at(field->parent));
1771 ERROR_FIELD(field, "%s lacks a file description",
1772 file->name);
1773 return 0;
1774 }
1775 }
1776 // Better to report an error than to fail mysteriously with "0 errors".
1777 if( yydebug || parse_error_count() == 0 ) {
1778 if( field->type == FldInvalid ) {
1779 ERROR_FIELD(field, "line %d: %s %s requires PICTURE",
1780 field->line, field->level_str(), field->name);
1781
1782 } else {
1783 dbgmsg("%s: error: data item %s #" HOST_SIZE_T_PRINT_UNSIGNED
1784 " '%s' capacity %u rejected",
1785 __func__,
1786 3 + cbl_field_type_str(field->type),
1787 (fmt_size_t)isym, field->name, field->data.capacity);
1788 }
1789 }
1790 return 0;
1791 }
1792
1793 if(! (field->data.memsize == 0 || field_size(field) <= field->data.memsize) ) {
1794 dbgmsg( "%s:%d: #" HOST_SIZE_T_PRINT_UNSIGNED ": invalid: %s", __func__, __LINE__,
1795 (fmt_size_t)symbol_index(p), field_str(cbl_field_of(p)) );
1796 }
1797 assert(field->data.memsize == 0 || field_size(field) <= field_memsize(field));
1798 assert( !(field->data.memsize > 0 && symbol_explicitly_redefines(field)) );
1799 }
1800
1801 // A shared record area has no 01 child because that child redefines its parent.
1802 for( auto sharer : shared_record_areas ) {
1803 auto redefined = cbl_field_of(symbol_at(sharer->parent));
1804 sharer->data.capacity = redefined->data.capacity;
1805 }
1806
1807 for( p = symbols_begin(first); p < symbols_end(); p++ ) {
1808 if( p->type != SymField ) continue;
1809 cbl_field_t *field = cbl_field_of(p);
1810 if( field->type == FldForward ) continue;
1811 if( field->type == FldSwitch ) continue;
1812 if( field->level == 0 && field->is_key_name() ) continue;
1813 if( is_literal(field) && field->var_decl_node != NULL ) continue;
1814
1815 // If the field is a constant for a figconstant, just use it.
1816 if( field->level != 0 && field->has_attr(constant_e) ) {
1817 auto fig = cbl_figconst_field_of(field->data.initial);
1818 if( fig ) {
1819 field->var_decl_node = fig->var_decl_node;
1820 continue;
1821 }
1822 }
1823
1824 if( field->is_typedef() ) {
1825 auto isym = end_of_group( symbol_index(p) );
1826 p = symbol_at(--isym);
1827 continue;
1828 }
1829
1830 // Verify REDEFINing field has no ODO components
1831 const cbl_field_t * parent = symbol_redefines(field);
1832 if( parent && !is_record_area(parent) && is_variable_length(field) ) {
1833 ERROR_FIELD(field, "line %d: REDEFINES field %s cannot be variable length",
1834 field->line, field->name);
1835 return 0;
1836 }
1837
1838 if( field->type == FldInvalid ) {
1839 dbgmsg("%s:%d: %s", __func__, __LINE__, field_str(field));
1840 ERROR_FIELD(field, "line %d: %s %s requires PICTURE",
1841 field->line, field->level_str(), field->name);
1842 continue;
1843 }
1844
1845 assert( ! field->is_typedef() );
1846
1847 if( parsed_ok ) parser_symbol_add(field);
1848 }
1849
1850 finalize_symbol_map2();
1851 if( yydebug ) dump_symbol_map2();
1852
1853 build_symbol_map();
1854
1855 int ninvalid = 0;
1856 for( p = symbols_begin(first); p < symbols_end(); p++ ) {
1857 if( p->type == SymFile ) { // now do the files
1858 auto& file = *cbl_file_of(p);
1859 if( !file.varying_size.explicitly ) {
1860 auto sizes = symbol_file_record_sizes( &file );
1861 file.varying_size = sizes;
1862 }
1863 file.deforward();
1864 if( ! file.validate() ) {
1865 ninvalid++;
1866 continue;
1867 }
1868 if( parsed_ok ) parser_file_add(&file);
1869 }
1870 }
1871
1872 symbols_dump(symbols.first_program, true);
1873
1874 symbols.procedures = p - symbols_begin();
1875
1876 return ninvalid > 0? 0 : symbols.procedures;
1877 }
1878
1879 size_t
1880 symbol_index() {
1881 assert( symbols.first_program <= symbols.nelem );
1882 return symbols.nelem - symbols.first_program;
1883 }
1884
1885 size_t
1886 symbol_index( const struct symbol_elem_t *e ) {
1887 assert(e);
1888 size_t isym = symbols.index(e);
1889 assert( isym < symbols.nelem );
1890 return isym;
1891 }
1892
1893 // Match on name (implied: of forward declaration).
1894 static int
1895 defined_fwd_cmp( const void *K, const void *E ) {
1896 const struct symbol_elem_t
1897 *k=static_cast<const struct symbol_elem_t *>(K),
1898 *e=static_cast<const struct symbol_elem_t *>(E);
1899
1900 if( k->type != SymField ) {
1901 cbl_errx( "%s: key must be field", __func__);
1902 }
1903 if( k->type != e->type ) return 1;
1904 if( k->program != e->program ) return 1;
1905
1906 // Matches if names match, and both are fields in the same program.
1907 // A forward declaration doesn't have parent because only its name is mentioned.
1908 return strcasecmp(cbl_field_of(k)->name, cbl_field_of(e)->name);
1909 }
1910
1911 /*
1912 * Given a symbol index that may be forward reference, return the
1913 * "resolved" field, if extant, else the forward field. Forward
1914 * references remain in the symbol table and their index may appear in,
1915 * for example, cbl_file_t symbols.
1916 */
1917 struct cbl_field_t *
1918 symbol_field_forward( size_t index ) {
1919 assert( index < symbols.nelem );
1920 symbol_elem_t *e = symbol_at(index);
1921 if( (e->type != SymField) ) {
1922 dbgmsg("%s: logic error: #" HOST_SIZE_T_PRINT_UNSIGNED " is %s",
1923 __func__, (fmt_size_t)index, symbol_type_str(e->type));
1924 }
1925 assert(e->type == SymField);
1926
1927 if( cbl_field_of(e)->type == FldForward ) {
1928
1929 symbol_elem_t *start = symbols_begin(++index);
1930 size_t nelem = symbols_end() - start;
1931
1932 struct symbol_elem_t *kid =
1933 static_cast<struct symbol_elem_t *>(lfind( e, start,
1934 &nelem, sizeof(*e),
1935 defined_fwd_cmp ) );
1936 if( kid ) {
1937 return cbl_field_of(kid);
1938 }
1939 }
1940 return cbl_field_of(e);
1941 }
1942
1943 struct symbol_elem_t *
1944 symbol_parent( const struct symbol_elem_t *e ) {
1945 assert(e);
1946 assert(e->type == SymField);
1947 assert(cbl_field_of(e)->type != FldInvalid);
1948
1949 if( cbl_field_of(e)->parent == 0 ) {
1950 return NULL;
1951 }
1952
1953 symbol_elem_t *p = symbols.elems + cbl_field_of(e)->parent;
1954
1955 assert( symbols.elems < p && p < symbols.elems + symbols.nelem );
1956
1957 return p;
1958 }
1959
1960 static bool
1961 had_picture( const cbl_field_t *field ) {
1962 if( is_elementary(field->type) ) {
1963 switch(field->type) {
1964 case FldAlphanumeric:
1965 // VALUE string for alphanumeric might mean no PICTURE.
1966 return field->data.initial == NULL;
1967 case FldNumericDisplay:
1968 case FldNumericEdited:
1969 case FldAlphaEdited:
1970 return true;
1971 case FldPointer:
1972 case FldPacked:
1973 case FldNumericBinary:
1974 case FldNumericBin5:
1975 case FldFloat:
1976 break;
1977 default:
1978 break;
1979 }
1980 }
1981 return false;
1982 }
1983
1984 void
1985 name_queue_t::dump( const char tag[] ) const {
1986 if( ! (yydebug ) ) return;
1987 int i=0;
1988 for( const auto& namelocs : this->c ) {
1989 static char line[256];
1990 char *p = line;
1991 const char *sep = "";
1992 for( auto nameloc : namelocs ) {
1993 p += snprintf( p, line + sizeof(line) - p, "%s%s", sep, nameloc.name );
1994 sep = "::";
1995 }
1996 dbgmsg("name_queue: %s: %2d: %s", tag, ++i, line);
1997 }
1998 if( empty() ) {
1999 dbgmsg("name_queue: %s: is empty", tag);
2000 }
2001 }
2002
2003 #if 0
2004 /*
2005 * When adding a symbol, set the parent as an offset into the symbol table.
2006 */
2007 static symbol_elem_t *
2008 symbol_in_file( symbol_elem_t *e ) {
2009
2010 auto beg = std::reverse_iterator<symbol_elem_t *>(e);
2011 auto end = std::reverse_iterator<symbol_elem_t *>(symbols_begin());
2012 auto p = std::find_if( beg, end,
2013 []( const symbol_elem_t& elem ) {
2014 return elem.type == SymFilename;
2015 } );
2016
2017 return p != end? &*p : NULL;
2018 }
2019 #endif
2020
2021 static cbl_field_t *
2022 symbol_field_parent_set( cbl_field_t *field )
2023 {
2024 if( field->level == 01 ) return NULL;
2025 if( field->level == 77 ) return NULL;
2026 if( field->level == 78 ) return NULL;
2027
2028 struct symbol_elem_t *e = symbols.elems + symbols.nelem - 1;
2029 const struct symbol_elem_t *first = symbols.elems + symbols.first_program;
2030
2031 for( ; field->parent == 0 && e >= first; e-- ) {
2032 if( ! (e->type == SymField && cbl_field_of(e)->level > 0) ) {
2033 continue; // level 0 fields are not user-declared symbols
2034 }
2035
2036 cbl_field_t *prior = cbl_field_of(e);
2037
2038 if( prior->level == 77 || prior->level == 78 ) {
2039 switch(field->level) {
2040 case 66: case 88:
2041 break;
2042 default:
2043 return NULL; // 77/78 cannot be a parent
2044 }
2045 }
2046
2047 if( prior->level == field->level ) {
2048 auto redefined = symbol_redefines(prior);
2049 if( redefined ) prior = redefined;
2050 field->parent = prior->parent;
2051 return cbl_field_of(symbol_at(field->parent));
2052 }
2053
2054 if( prior->level < field->level ) {
2055 if( prior->has_attr(same_as_e) ) {
2056 ERROR_FIELD(prior, "%s created with SAME AS or TYPE TO, cannot have new member %s",
2057 prior->name, field->name);
2058 return NULL;
2059 }
2060 field->parent = e - symbols.elems;
2061 if( 1 < field->level && field->level < 50 ) {
2062 if( had_picture(prior) ) {
2063 ERROR_FIELD(prior, "group %s cannot have PICTURE clause", prior->name);
2064 return NULL;
2065 }
2066 prior->type = FldGroup;
2067 field->attr |= numeric_group_attrs(prior);
2068 }
2069 // verify level 88 domain value
2070 if( is_numeric(prior) && field->level == 88 ) {
2071 // domain array terminated by an element with a NULL name (value)
2072 auto edom = field->data.domain_of();
2073 while( edom->first.name() ) edom++;
2074
2075 bool all_numeric =
2076 std::all_of( field->data.domain_of(), edom,
2077 []( const cbl_domain_t& domain ) {
2078 switch( cbl_figconst_of(domain.first.name()) ) {
2079 case normal_value_e:
2080 // parser ensures first.is_numeric == last.is_numeric
2081 return domain.first.is_numeric &&
2082 domain.last.is_numeric;
2083 case zero_value_e:
2084 return true;
2085 default:
2086 break;
2087 }
2088 return false;
2089 } );
2090 if( ! all_numeric ) {
2091 auto loc = symbol_field_location(0);
2092 error_msg(loc, "%s %s invalid VALUE for numeric type %s",
2093 field->level_str(), field->name, prior->name);
2094 }
2095 }
2096 return prior;
2097 }
2098 }
2099 return NULL;
2100 }
2101
2102 class parent_elem_set
2103 {
2104 private:
2105 size_t parent_index;
2106 public:
2107 explicit parent_elem_set( size_t parent_index )
2108 : parent_index(parent_index)
2109 {}
2110 void operator()( struct symbol_elem_t& e ) {
2111 // cannot use cbl_field_of, because symbols.elems not yet ready
2112 assert(e.type == SymField);
2113 e.elem.field.parent = this->parent_index;
2114 }
2115 };
2116
2117 static symbol_elem_t
2118 add_token( symbol_elem_t sym ) {
2119 assert(sym.type == SymSpecial);
2120 sym.elem.special.token = keyword_tok(sym.elem.special.name);
2121 return sym;
2122 }
2123
2124 /*
2125 * When adding registers, be sure to add a complementary cblc_field_t
2126 * in libgcobol/constants.cc.
2127 */
2128 void
2129 symbol_table_init(void) {
2130 assert(symbols.fd == -1);
2131 assert(symbols.nelem == 0);
2132
2133 symbol_table_t table = symbol_table_extend();
2134
2135 // Insert known contants at the top of an empty table.
2136 // Constants are signified by their attribute
2137 // Be warned that ZEROS plays for both sides. It is defined here as
2138 // quoted, but in context it can be the value zero at run-time. Yes, it
2139 // is an annoyance.
2140 static char zeroes_for_null_pointer[8] = {0,0,0,0,0,0,0,0};
2141
2142 // These should match the definitions in libgcobol/constants.cc
2143 static cbl_field_t constants[] = {
2144 { 0, FldAlphanumeric, FldInvalid, space_value_e | constq, 0, 0, 0, nonarray, 0,
2145 "SPACE", 0, {}, {1,1,0,0, " \0\xFF"}, NULL },
2146 { 0, FldAlphanumeric, FldInvalid, space_value_e | constq , 0, 0, 0, nonarray, 0,
2147 "SPACES", 0, {}, {1,1,0,0, " \0\xFF"}, NULL },
2148 { 0, FldAlphanumeric, FldInvalid, low_value_e | constq, 0, 0, 0, nonarray, 0,
2149 "LOW_VALUES", 0, {}, {1,1,0,0, "L\0\xFF"}, NULL },
2150 { 0, FldAlphanumeric, FldInvalid, zero_value_e | constq, 0, 0, 0, nonarray, 0,
2151 "ZEROS", 0, {}, {1,1,0,0, "0"}, NULL },
2152 { 0, FldAlphanumeric, FldInvalid, high_value_e | constq, 0, 0, 0, nonarray, 0,
2153 "HIGH_VALUES", 0, {}, {1,1,0,0, "H\0\xFF"}, NULL },
2154 // IBM standard: QUOTE is a double-quote unless APOST compiler option
2155 { 0, FldAlphanumeric, FldInvalid, quote_value_e | constq , 0, 0, 0, nonarray, 0,
2156 "QUOTES", 0, {}, {1,1,0,0, "\"\0\xFF"}, NULL },
2157 { 0, FldPointer, FldPointer, constq , 0, 0, 0, nonarray, 0,
2158 "NULLS", 0, {}, {8,8,0,0, zeroes_for_null_pointer}, NULL },
2159 // IBM defines TALLY
2160 // 01 TALLY GLOBAL PICTURE 9(5) USAGE BINARY VALUE ZERO.
2161 { 0, FldNumericBin5, FldInvalid, signable_e, 0, 0, 0, nonarray, 0,
2162 "_TALLY", 0, {}, {16, 16, MAX_FIXED_POINT_DIGITS, 0, NULL}, NULL },
2163 // 01 ARGI is the current index into the argv array
2164 { 0, FldNumericBin5, FldInvalid, signable_e, 0, 0, 0, nonarray, 0,
2165 "_ARGI", 0, {}, {16, 16, MAX_FIXED_POINT_DIGITS, 0, NULL}, NULL },
2166
2167 // These last two don't require actual storage; they get BOOL var_decl_node
2168 // in parser_symbol_add()
2169 { 0, FldConditional, FldInvalid, constant_e , 0, 0, 0, nonarray, 0,
2170 "_VERY_TRUE", 0, {}, {1,1,0,0, ""}, NULL },
2171 { 0, FldConditional, FldInvalid, constant_e , 0, 0, 0, nonarray, 0,
2172 "_VERY_FALSE", 0, {}, {1,1,0,0, ""}, NULL },
2173 };
2174 for( struct cbl_field_t *f = constants;
2175 f < constants + COUNT_OF(constants); f++ ) {
2176 f->our_index = table.nelem;
2177 struct symbol_elem_t sym(SymField, 0);
2178 sym.elem.field = *f;
2179 table.elems[table.nelem++] = sym;
2180 }
2181
2182 static symbol_elem_t environs[] = {
2183 { symbol_elem_t{ 0, cbl_special_name_t{0, CONSOLE_e, "CONSOLE", 0, "/dev/stdout"}} }, // stdout in DISPLAY; stdin in ACCEPT
2184
2185 { symbol_elem_t{ 0, cbl_special_name_t{0, STDIN_e, "STDIN", 0, "/dev/stdin"}} },
2186 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSIN_e, "SYSIN", 0, "/dev/stdin"}} },
2187 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSIPT_e, "SYSIPT", 0, "/dev/stdin"}} },
2188
2189 { symbol_elem_t{ 0, cbl_special_name_t{0, STDOUT_e, "STDOUT", 0, "/dev/stdout"}} },
2190 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSOUT_e, "SYSOUT", 0, "/dev/stdout"}} },
2191 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSLIST_e, "SYSLIST", 0, "/dev/stdout"}} },
2192 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSLST_e, "SYSLST", 0, "/dev/stdout"}} },
2193
2194 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSPUNCH_e, "SYSPUNCH", 0, "/dev/stderr"}} },
2195 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSPCH_e, "SYSPCH", 0, "/dev/stderr"}} },
2196 { symbol_elem_t{ 0, cbl_special_name_t{0, STDERR_e, "STDERR", 0, "/dev/stderr"}} },
2197 { symbol_elem_t{ 0, cbl_special_name_t{0, SYSERR_e, "SYSERR", 0, "/dev/stderr"}} },
2198
2199 { symbol_elem_t{ 0, cbl_special_name_t{0, C01_e, "C01", 0, "/dev/null"}} },
2200 { symbol_elem_t{ 0, cbl_special_name_t{0, C02_e, "C02", 0, "/dev/null"}} },
2201 { symbol_elem_t{ 0, cbl_special_name_t{0, C03_e, "C03", 0, "/dev/null"}} },
2202 { symbol_elem_t{ 0, cbl_special_name_t{0, C04_e, "C04", 0, "/dev/null"}} },
2203 { symbol_elem_t{ 0, cbl_special_name_t{0, C05_e, "C05", 0, "/dev/null"}} },
2204 { symbol_elem_t{ 0, cbl_special_name_t{0, C06_e, "C06", 0, "/dev/null"}} },
2205 { symbol_elem_t{ 0, cbl_special_name_t{0, C07_e, "C07", 0, "/dev/null"}} },
2206 { symbol_elem_t{ 0, cbl_special_name_t{0, C08_e, "C08", 0, "/dev/null"}} },
2207 { symbol_elem_t{ 0, cbl_special_name_t{0, C09_e, "C09", 0, "/dev/null"}} },
2208 { symbol_elem_t{ 0, cbl_special_name_t{0, C10_e, "C10", 0, "/dev/null"}} },
2209 { symbol_elem_t{ 0, cbl_special_name_t{0, C11_e, "C11", 0, "/dev/null"}} },
2210 { symbol_elem_t{ 0, cbl_special_name_t{0, C12_e, "C12", 0, "/dev/null"}} },
2211 { symbol_elem_t{ 0, cbl_special_name_t{0, CSP_e, "CSP", 0, "/dev/null"}} },
2212 { symbol_elem_t{ 0, cbl_special_name_t{0, S01_e, "S01", 0, "/dev/null"}} },
2213 { symbol_elem_t{ 0, cbl_special_name_t{0, S02_e, "S02", 0, "/dev/null"}} },
2214 { symbol_elem_t{ 0, cbl_special_name_t{0, S03_e, "S03", 0, "/dev/null"}} },
2215 { symbol_elem_t{ 0, cbl_special_name_t{0, S04_e, "S04", 0, "/dev/null"}} },
2216 { symbol_elem_t{ 0, cbl_special_name_t{0, S05_e, "S05", 0, "/dev/null"}} },
2217 { symbol_elem_t{ 0, cbl_special_name_t{0, AFP_5A_e, "AFP-5A", 0, "/dev/null"}} },
2218 };
2219
2220 struct symbol_elem_t *p = table.elems + table.nelem;
2221 std::transform(environs, environs + COUNT_OF(environs), p, add_token);
2222
2223 table.nelem += COUNT_OF(environs);
2224
2225 assert(table.nelem < table.capacity);
2226
2227 /**
2228 * Debug register record
2229 01 DEBUG-ITEM.
2230 02 DEBUG-LINE PIC X(6).
2231 02 FILLER PIC X VALUE SPACE.
2232 02 DEBUG-NAME PIC X(30).
2233 02 FILLER PIC X VALUE SPACE.
2234 02 DEBUG-SUB-1 PIC S9999 SIGN IS LEADING SEPARATE CHARACTER.
2235 02 FILLER PIC X VALUE SPACE.
2236 02 DEBUG-SUB-2 PIC S9999 SIGN IS LEADING SEPARATE CHARACTER.
2237 02 FILLER PIC X VALUE SPACE.
2238 02 DEBUG-SUB-3 PIC S9999 SIGN IS LEADING SEPARATE CHARACTER.
2239 02 FILLER PIC X VALUE SPACE.
2240 02 DEBUG-CONTENTS PIC X(76).
2241 **/
2242
2243 static cbl_field_t debug_registers[] = {
2244 { 0, FldGroup, FldInvalid, global_e, 0,0,1, nonarray, 0,
2245 "DEBUG-ITEM", 0, {}, {132,132,0,0, NULL}, NULL },
2246 { 0, FldAlphanumeric, FldInvalid, global_e, 0,0,2, nonarray, 0,
2247 "DEBUG-LINE", 0, {}, {6,6,0,0, " "}, NULL },
2248 { 0, FldAlphanumeric, FldInvalid, 0, 0,0,2, nonarray, 0,
2249 "FILLER", 0, {}, {1,1,0,0, " "}, NULL },
2250 { 0, FldAlphanumeric, FldInvalid, global_e, 0,0,2, nonarray, 0,
2251 "DEBUG-NAME", 0, {}, {30,30,0,0, NULL}, NULL },
2252 { 0, FldAlphanumeric, FldInvalid, 0, 0,0,2, nonarray, 0,
2253 "FILLER", 0, {}, {1,1,0,0, " "}, NULL },
2254 { 0, FldNumericDisplay, FldInvalid, signable_e | global_e | leading_e | separate_e, 0,0,2, nonarray, 0,
2255 "DEBUG-SUB-1", 0, {}, {5,5,3,0, NULL}, NULL },
2256 { 0, FldAlphanumeric, FldInvalid, 0, 0,0,2, nonarray, 0,
2257 "FILLER", 0, {}, {1,1,0,0, " "}, NULL },
2258 { 0, FldNumericDisplay, FldInvalid, signable_e | global_e | leading_e | separate_e, 0,0,2, nonarray, 0,
2259 "DEBUG-SUB-2", 0, {}, {5,5,3,0, NULL}, NULL },
2260 { 0, FldAlphanumeric, FldInvalid, 0, 0,0,2, nonarray, 0,
2261 "FILLER", 0, {}, {1,1,0,0, " "}, NULL },
2262 { 0, FldNumericDisplay, FldInvalid, signable_e | global_e | leading_e | separate_e, 0,0,2, nonarray, 0,
2263 "DEBUG-SUB-3", 0, {}, {5,5,3,0, NULL}, NULL },
2264 { 0, FldAlphanumeric, FldInvalid, 0, 0,0,2, nonarray, 0,
2265 "FILLER", 0, {}, {1,1,0,0, " "}, NULL },
2266 { 0, FldAlphanumeric, FldInvalid, signable_e | global_e, 0,0,2, nonarray, 0,
2267 "DEBUG-CONTENTS", 0, {}, {76,76,0,0, NULL}, NULL },
2268 };
2269
2270 // debug registers
2271 assert(table.nelem + COUNT_OF(debug_registers) < table.capacity);
2272
2273 group_size_t group_size =
2274 std::accumulate(debug_registers,
2275 debug_registers + COUNT_OF(debug_registers), group_size_t());
2276 debug_registers[0].data.memsize =
2277 debug_registers[0].data.capacity = group_size.capacity();
2278
2279 auto debug_start = p = table.elems + table.nelem;
2280 p = std::transform(debug_registers,
2281 debug_registers + COUNT_OF(debug_registers), p, elementize);
2282 table.nelem = p - table.elems;
2283 assert(table.nelem < table.capacity);
2284 std::for_each(debug_start+1, p, parent_elem_set(debug_start - table.elems));
2285
2286 static cbl_field_t special_registers[] = {
2287 { 0, FldNumericDisplay, FldInvalid, 0, 0, 0, 0, nonarray, 0, "_FILE_STATUS",
2288 0, {}, {2,2,2,0, NULL}, NULL },
2289 { 0, FldNumericBin5, FldInvalid, 0, 0, 0, 0, nonarray, 0, "UPSI-0",
2290 0, {}, {2,2,4,0, NULL}, NULL },
2291 { 0, FldNumericBin5, FldInvalid, signable_e, 0, 0, 0, nonarray, 0, "RETURN-CODE",
2292 0, {}, {2,2,4,0, NULL}, NULL },
2293 { 0, FldNumericBin5, FldInvalid, 0, 0, 0, 0, nonarray, 0, "LINAGE-COUNTER",
2294 0, {}, {2,2,4,0, NULL}, NULL },
2295 { 0, FldLiteralA, FldInvalid, 0, 0, 0, 0, nonarray, 0, "_dev_stdin",
2296 0, {}, {0,0,0,0, "/dev/stdin"}, NULL },
2297 { 0, FldLiteralA, FldInvalid, constq, 0, 0, 0, nonarray, 0, "_dev_stdout",
2298 0, {}, {0,0,0,0, "/dev/stdout"}, NULL },
2299 { 0, FldLiteralA, FldInvalid, constq, 0, 0, 0, nonarray, 0, "_dev_stderr",
2300 0, {}, {0,0,0,0, "/dev/stderr"}, NULL },
2301 { 0, FldLiteralA, FldInvalid, constq, 0, 0, 0, nonarray, 0, "_dev_null",
2302 0, {}, {0,0,0,0, "/dev/null"}, NULL },
2303 };
2304
2305 // special registers
2306 assert(table.nelem + COUNT_OF(special_registers) < table.capacity);
2307
2308 p = table.elems + table.nelem;
2309 p = std::transform(special_registers,
2310 special_registers + COUNT_OF(special_registers),
2311 p, elementize);
2312 table.nelem = p - table.elems;
2313 assert(table.nelem < table.capacity);
2314
2315 // Initialize symbol table.
2316 symbols = table;
2317
2318 for( auto e = symbols.elems; e < symbols.elems + symbols.nelem; e++ ) {
2319 if( e->type == SymField ) {
2320 update_symbol_map2(e);
2321 }
2322 }
2323
2324 symbols.first_program = symbols.nelem;
2325
2326 symbols.registers.linage_counter = symbol_index(symbol_field(0,0,
2327 "LINAGE-COUNTER"));
2328 symbols.registers.file_status = symbol_index(symbol_field(0,0, "_FILE_STATUS"));
2329 symbols.registers.return_code = symbol_index(symbol_field(0,0, "RETURN-CODE"));
2330 symbols.registers.very_true = symbol_index(symbol_field(0,0, "_VERY_TRUE"));
2331 symbols.registers.very_false = symbol_index(symbol_field(0,0, "_VERY_FALSE"));
2332 }
2333
2334 /*
2335 * Add a symbol to the symbol table.
2336 */
2337 static struct symbol_elem_t *
2338 symbol_add( struct symbol_elem_t *elem )
2339 {
2340 assert(symbols.capacity > 0); // initialized
2341
2342 if( symbols.nelem == symbols.capacity ) {
2343 symbol_table_extend();
2344 };
2345
2346 assert(symbols.nelem < symbols.capacity); // not at capacity
2347
2348 if( elem->type == SymField ) {
2349 // Place the [soon-to-be] index of this field into the field
2350 cbl_field_of(elem)->our_index = symbols.nelem;
2351 }
2352
2353 struct symbol_elem_t *p =
2354 static_cast<struct symbol_elem_t *>(lsearch( elem, symbols.elems,
2355 &symbols.nelem, sizeof(*elem),
2356 symbol_elem_cmp ) );
2357 assert(symbols.nelem > 1);
2358
2359 if( is_program(*p) ) {
2360 assert(p->program == 0 || p->elem.label.os_name != NULL);
2361 p->program = p - symbols.elems;
2362 }
2363
2364 if( p->program == 0 ) {
2365 p->program = p[-1].program;
2366 }
2367
2368 return p;
2369 }
2370
2371 static symbol_elem_t *
2372 symbol_append( const symbol_elem_t& elem ) {
2373 if( symbols.nelem == symbols.capacity ) {
2374 symbol_table_extend();
2375 };
2376
2377 auto e = symbols.elems + symbols.nelem++;
2378 *e = elem;
2379 return e;
2380 }
2381
2382 cbl_label_t *
2383 cbl_perform_tgt_t::finally( size_t program ) {
2384 assert(0 < ito);
2385 static const char fini[] = "_fini";
2386 cbl_label_t proto = *to();
2387 auto p = proto.name + strlen(proto.name);
2388 auto n = snprintf(p, proto.name + sizeof(proto.name) - p, "%s", fini);
2389 assert(n < int(sizeof(fini)));
2390 symbol_elem_t sym = {}, *e;
2391 sym.type = SymLabel;
2392 sym.program = program;
2393 sym.elem.label = proto;
2394 e = symbol_add(&sym);
2395 ifrom = symbol_index(e);
2396 return cbl_label_of(e);
2397 }
2398
2399 struct symbol_elem_t *
2400 symbol_file_add( size_t program, cbl_file_t *file ) {
2401 auto e = std::find_if( symbols_begin(program), symbols_end(),
2402 [file]( const auto& elem ) {
2403 if( elem.type == SymFile ) {
2404 auto f = cbl_file_of(&elem);
2405 return 0 == strcasecmp(f->name, file->name);
2406 }
2407 return false;
2408 } );
2409 if( e != symbols_end() ) { // duplicate SELECT filenames not allowed
2410 auto f = cbl_file_of(e);
2411 file->line = f->line; // use called structure to capture prior line
2412 return NULL;
2413 }
2414
2415 symbol_elem_t sym{ SymFile, program };
2416 sym.elem.file = *file;
2417
2418 e = symbol_add(&sym);
2419
2420 const auto& f = *cbl_file_of(e);
2421 if( f.same_record_as > 0 ) { // add to list of files sharing one record area
2422 same_record_areas[f.same_record_as].insert(symbol_index(e));
2423 }
2424
2425 return e;
2426 }
2427
2428 symbol_elem_t *
2429 symbol_alphabet_add( size_t program, const cbl_alphabet_t *alphabet ) {
2430 symbol_elem_t sym{ SymAlphabet, program };
2431 sym.elem.alphabet = *alphabet;
2432 return symbol_add(&sym);
2433 }
2434
2435 uint64_t
2436 numeric_group_attrs( const cbl_field_t *field ) {
2437 static const uint64_t inherit = signable_e | leading_e | separate_e | big_endian_e;
2438 static_assert(sizeof(cbl_field_t::type) < sizeof(inherit), "need bigger type");
2439 assert(field);
2440 if( field->type == FldNumericDisplay || field->type == FldGroup ) {
2441 if( field->parent > 0 && symbol_at(field->parent)->type == SymField ) {
2442 cbl_field_t *parent = parent_of(field);
2443 assert(parent);
2444 return inherit & parent->attr;
2445 }
2446 }
2447 return 0;
2448 }
2449
2450 /*
2451 * "The essential characteristics of a type, which is identified by
2452 * its type- name, are the relative positions and lengths of the
2453 * elementary items defined in the type declaration, and the ALIGNED,
2454 * BLANK WHEN ZERO, DYNAMIC LENGTH, JUSTIFIED, PICTURE, SIGN,
2455 * SYNCHRONIZED, and USAGE clauses specified for each of these
2456 * elementary items"
2457 */
2458 struct symbol_elem_t *
2459 symbol_typedef_add( size_t program, struct cbl_field_t *field ) {
2460 assert(field);
2461 assert(field->is_typedef());
2462
2463 if( field->is_strongdef() && field->level != 1 ) {
2464 ERROR_FIELD(field, "%s %s STRONG TYPEDEF must be level 01",
2465 field->level_str(), field->name);
2466 return NULL;
2467 }
2468
2469 // Might have just been added to the symbol table.
2470 auto e = symbols_end() - 1;
2471 assert( symbols_begin() < e );
2472 if( e->type == SymField ) {
2473 const cbl_field_t * f = cbl_field_of(e);
2474 if( f == field ) return e;
2475 }
2476
2477 symbol_elem_t elem{ program, *field };
2478
2479 e = symbol_add( &elem );
2480
2481 return e;
2482 }
2483
2484 typedef std::map <std::string, size_t > namemap_t;
2485 static std::map <size_t, namemap_t > numeric_constants;
2486
2487 /*
2488 * Add a Cobol variable/literal to the symbol table.
2489 *
2490 * Each time the filename changes, a "filename" symbol is added to the
2491 * symbol table. We find what file a symbol was defined in by
2492 * searching back from the symbol for a filename entry.
2493 *
2494 * Fields may be function pointers too, from dlopen(3).
2495 *
2496 * Most symbols are Cobol variables of type cbl_field_t. Duplicate
2497 * names are allowed; they just can't be referenced.
2498 *
2499 * The passed parameter contains two pointers; the initial value and
2500 * the picture. Except for inherited types, these pointers are NOT
2501 * changed. Make them point where you want them to point.
2502 *
2503 * Literals have an initial pointer only; the picture NULL.
2504 *
2505 * Returns a pointer to the added symbol, always.
2506 */
2507 struct symbol_elem_t *
2508 symbol_field_add( size_t program, struct cbl_field_t *field )
2509 {
2510 field->our_index = symbols.nelem;
2511 const cbl_field_t *parent = symbol_field_parent_set( field );
2512 if( parent && parent->type == FldGroup) {
2513 // Inherit effects of parent's USAGE, as though it appeared 1st in the
2514 // member's definition.
2515 static const size_t inherit = global_e | external_e | local_e | linkage_e;
2516 field->attr = inherit & parent->attr;
2517 field->attr |= numeric_group_attrs(parent);
2518 field->usage = parent->usage;
2519 // BINARY-LONG, for example, sets capacity.
2520 if( is_numeric(parent->usage) && parent->data.capacity > 0 ) {
2521 field->type = parent->usage;
2522 field->data = parent->data;
2523 field->data = 0; // cppcheck-suppress redundantAssignment
2524 // // cppcheck doesn't understand multiple overloaded operator=
2525 field->data.initial = NULL;
2526 }
2527 }
2528
2529 if( is_forward(field) ) {
2530 auto *e = symbol_field( program, field->parent, field->name );
2531 if( e ) {
2532 field = cbl_field_of(e);
2533 if( is_constant(field) && field->type == FldNumericBin5 ) {
2534 cbl_name_t lname;
2535 std::transform( field->name, field->name + strlen(field->name) + 1,
2536 lname, tolower );
2537 numeric_constants[program][lname] = symbol_index(e);
2538 }
2539 return e;
2540 }
2541 }
2542
2543 if( strlen(field->name) == 6 && 0 == strcasecmp("FILLER", field->name) ) {
2544 field->attr |= filler_e;
2545 }
2546 if( field->name[0] == '\0' ) {
2547 field->attr |= filler_e;
2548 }
2549
2550 symbol_elem_t key { program, *field };
2551
2552 // Literals must have an initial value;
2553 assert( !is_literal(field) || field->data.initial );
2554
2555 /*
2556 * Field names need not be unique. They exist in the symbol table
2557 * (and in memory) regardless, but only unique names may be referenced.
2558 * We don't use symbol_add, because it looks up the symbol by name.
2559 */
2560
2561 // ensure the table has room
2562 if( symbols.nelem == symbols.capacity ) {
2563 symbol_table_extend();
2564 };
2565
2566 assert(symbols.nelem < symbols.capacity); // not at capacity
2567
2568 // append the symbol
2569 struct symbol_elem_t *e = symbols_end();
2570 *e = key;
2571 symbols.nelem++;
2572
2573 field = cbl_field_of(e);
2574 if( is_constant(field) && field->type == FldNumericBin5 ) {
2575 cbl_name_t lname;
2576 std::transform( field->name, field->name + strlen(field->name) + 1,
2577 lname, tolower );
2578 numeric_constants[program][lname] = symbol_index(e);
2579 }
2580
2581 update_symbol_map2( e );
2582 return e;
2583 }
2584
2585 /*
2586 * TYPEDEF is relevant only in Data Division.
2587 */
2588 struct symbol_elem_t *
2589 symbol_typedef( size_t program, const char name[] )
2590 {
2591 auto beg = std::reverse_iterator<symbol_elem_t *>(symbols_end());
2592 auto end = std::reverse_iterator<symbol_elem_t *>(symbols_begin(program));
2593
2594 auto p = std::find_if( beg, end,
2595 [name]( const symbol_elem_t& sym ) {
2596 if( sym.type == SymField ) {
2597 auto f = cbl_field_of(&sym);
2598 if( f->has_attr(typedef_e) ) {
2599 return 0 == strcasecmp(name, f->name);
2600 }
2601 }
2602 return false;
2603 } );
2604
2605 return p != end? &*p : NULL;
2606 }
2607
2608 /*
2609 * Search backwards during symbol-table construction for nearest name.
2610 */
2611 symbol_elem_t *
2612 symbol_field( size_t program, size_t parent, const char name[] )
2613 {
2614 class match_field {
2615 size_t program, parent;
2616 const char *name;
2617 public:
2618 match_field( size_t program, size_t parent, const char name[] )
2619 : program(program)
2620 , parent(parent)
2621 , name(name)
2622 {}
2623 bool operator()( const symbol_elem_t& sym ) const {
2624 if( sym.type != SymField ) return false;
2625 if( sym.program != program ) return false;
2626
2627 const auto& field = *cbl_field_of(&sym);
2628
2629 if( parent > 0 && parent != field.parent ) return false;
2630 if( field.is_typedef() ) return false;
2631
2632 return 0 == strcasecmp(name, field.name);
2633 }
2634 };
2635
2636 auto beg = std::reverse_iterator<symbol_elem_t *>(symbols_end());
2637 auto end = std::reverse_iterator<symbol_elem_t *>(symbols_begin(program));
2638 auto p = std::find_if( beg, end, match_field(program, parent, name) );
2639
2640 return p != end? &*p : NULL;
2641 }
2642
2643 // cppcheck-suppress-begin [CastIntegerToAddressAtReturn] obviously not true
2644 symbol_elem_t *
2645 symbol_register( const char name[] )
2646 {
2647 auto p = std::find_if(symbols_begin(), symbol_at(symbols.first_program),
2648 [len = strlen(name), name]( auto e ) {
2649 if( e.type == SymField ) {
2650 if( strlen(cbl_field_of(&e)->name) == len ) {
2651 return 0 == strcasecmp(cbl_field_of(&e)->name, name);
2652 }
2653 }
2654 return false;
2655 } );
2656
2657 return p;
2658 }
2659 // cppcheck-suppress-end [CastIntegerToAddressAtReturn]
2660
2661 // Find current 01 record during Level 66 construction.
2662 const symbol_elem_t *
2663 symbol_field_current_record() {
2664 assert(symbols.nelem > 0);
2665 size_t program = symbols_end()[-1].program;
2666 auto beg = std::reverse_iterator<symbol_elem_t *>(symbols_end());
2667 auto end = std::reverse_iterator<symbol_elem_t *>(symbols_begin(program));
2668 auto p = std::find_if( beg, end,
2669 []( const auto& elem ) {
2670 if( elem.type == SymField ) {
2671 auto f = cbl_field_of(&elem);
2672 return f->level == 1;
2673 }
2674 return false;
2675 } );
2676 return p != end? &*p : NULL;
2677 }
2678
2679
2680 struct symbol_elem_t *
2681 symbol_field_forward_add( size_t program, size_t parent,
2682 const char name[], int line )
2683 {
2684 auto e = symbol_field(program, parent, name);
2685 if( e ) return e;
2686
2687 struct cbl_field_t field = { 0,
2688 FldForward, FldInvalid, 0, parent, 0, 0,
2689 nonarray, line, "",
2690 0, cbl_field_t::linkage_t(),
2691 {0,0,0,0, " "}, NULL };
2692 if( sizeof(field.name) < strlen(name) ) {
2693 dbgmsg("%s:%d: logic error: name %s too long", __func__, __LINE__, name);
2694 return NULL;
2695 }
2696 strcpy( field.name, name);
2697 return symbol_field_add( program, &field );
2698 }
2699
2700 struct symbol_elem_t *
2701 symbol_literalA( size_t program, const char name[] )
2702 {
2703 cbl_field_t field = {};
2704 field.type = FldLiteralA;
2705 field.data.initial = name;
2706 field.attr = constq;
2707
2708 struct symbol_elem_t key { program, field };
2709
2710 symbol_elem_t *start = symbols_begin(key.program), *e;
2711 size_t nelem = symbols_end() - start;
2712
2713 e = static_cast<struct symbol_elem_t *>(lfind( &key, start,
2714 &nelem, sizeof(key),
2715 symbol_elem_cmp ) );
2716 return e;
2717 }
2718
2719 struct symbol_elem_t *
2720 symbol_file( size_t program, const char name[] ) {
2721 size_t nelem = symbols.nelem;
2722 symbol_elem_t key{ SymFile, program }, *e = &key;
2723
2724 assert(strlen(name) < sizeof(key.elem.file.name));
2725 strcpy(key.elem.file.name, name);
2726
2727 // cppcheck-suppress-begin [knownConditionTrueFalse]
2728 do {
2729 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
2730 &nelem, sizeof(*e),
2731 symbol_elem_cmp ) );
2732 if( e ) break;
2733 key.program = cbl_label_of(symbol_at(key.program))->parent;
2734 if( key.program == 0 ) break; // no file without a program
2735 } while( !e );
2736 // cppcheck-suppress-end [knownConditionTrueFalse]
2737
2738 if( e ) {
2739 assert(e->type == SymFile);
2740 return e;
2741 }
2742
2743 // perhaps a record name?
2744 for( e = symbol_field(program, 0, name); e != NULL; e = symbol_parent(e) ) {
2745 if( e->type == SymFile ) {
2746 return e;
2747 }
2748 if( e->type != SymField ) {
2749 dbgmsg("%s:%d: '%s' is not a file and has parent of type %s",
2750 __func__, __LINE__, name, symbol_type_str(e->type));
2751 return NULL;
2752 }
2753 if( symbol_index(e) == 0 ) {
2754 dbgmsg("%s:%d: '%s' is not a file and has no parent",
2755 __func__, __LINE__, name);
2756 return NULL;
2757 }
2758 }
2759
2760 assert(!e);
2761 return e;
2762 }
2763
2764 struct symbol_elem_t *
2765 symbol_field_alias( struct symbol_elem_t *e, const char name[] )
2766 {
2767 cbl_field_t alias = *cbl_field_of(e);
2768 cbl_field_data_t data = { alias.data.memsize, alias.data.capacity };
2769 alias.data = data;
2770 alias.data.memsize = 0;
2771
2772 assert(strlen(name) < sizeof(alias.name));
2773 strcpy(alias.name, name);
2774
2775 alias.level = 66;
2776 alias.parent = symbol_index(e);
2777 alias.var_decl_node = NULL;
2778
2779 return symbol_field_add(e->program, &alias);
2780 }
2781
2782 struct symbol_elem_t *
2783 symbol_field_alias2( struct symbol_elem_t *e, struct symbol_elem_t *e2,
2784 const char name[] )
2785 {
2786 assert(cbl_field_of(e)->data.picture == NULL);
2787 e = symbol_field_alias(e, name);
2788
2789 cbl_field_t& alias = *cbl_field_of(e);
2790 alias.type = FldGroup;
2791
2792 // store THRU symbol in data.picture, capacity computed by extend_66_capacity
2793 alias.data.picture = reinterpret_cast<char*>(e2);
2794
2795 return e;
2796 }
2797
2798 static bool
2799 target_in_src( const cbl_field_t *tgt, const cbl_field_t *src ) {
2800 size_t isrc = field_index(src);
2801 while( tgt->parent > 0 ) {
2802 if( tgt->parent == isrc ) return true;
2803 auto e = symbol_at(tgt->parent);
2804 if( e->type != SymField ) break;
2805 tgt = cbl_field_of(e);
2806 }
2807 return false;
2808 }
2809
2810 class elem_group_t {
2811 const symbol_elem_t *bog, *eog;
2812 public:
2813 elem_group_t( const symbol_elem_t *bog, const symbol_elem_t *eog )
2814 : bog(bog), eog(eog) {}
2815 const symbol_elem_t *begin() const { return bog; }
2816 const symbol_elem_t *end() const { return eog; }
2817 };
2818
2819 static size_t
2820 seek_parent( const symbol_elem_t *e, size_t level ) {
2821 size_t program = e->program;
2822 const cbl_field_t *field = cbl_field_of(e);
2823 while( program == e->program && level <= field->level ) {
2824 if( e->type != SymField ) break;
2825 auto f = cbl_field_of(e);
2826 if( f->parent == 0 ) break;
2827 e = symbol_at(f->parent);
2828 }
2829 return symbol_index(e);
2830 }
2831
2832 /*
2833 * For SAME AS definition, copy the field metadata and update the parent.
2834 * For a group, create new fields and copy members recursively.
2835 * Precondition: both fields exist in the symbol table.
2836 * Postcondition: return final element copied.
2837 *
2838 * "The condition-name entries for a particular conditional variable
2839 * shall immediately follow the entry describing the item...."
2840 */
2841 struct symbol_elem_t *
2842 symbol_field_same_as( cbl_field_t *tgt, const cbl_field_t *src ) {
2843 if( target_in_src(tgt, src) ) {
2844 ERROR_FIELD(tgt, "%s %s may not reference itself as part of %s %s",
2845 tgt->level_str(), tgt->name, src->level_str(), src->name);
2846 return NULL;
2847 }
2848 if( tgt->level == 77 && src->type == FldGroup ) {
2849 ERROR_FIELD(tgt, "%s %s TYPE TO %s must be an elementary item",
2850 tgt->level_str(), tgt->name, src->name);
2851 return NULL;
2852 }
2853 auto last_elem = symbol_at(field_index(tgt));
2854 tgt->same_as(*src, src->is_typedef());
2855
2856 size_t isrc = field_index(src);
2857
2858 symbol_elem_t *bog = symbol_at(isrc);
2859 symbol_elem_t *eog = symbol_at_impl(end_of_group(isrc), true);
2860
2861 if( src->type != FldGroup ) {
2862 // For scalar, check for Level 88, which if extant must follow immediately.
2863 eog = std::find_if( bog + 1,
2864 symbols_end(),
2865 []( const auto& elem ) {
2866 if( elem.type == SymField ) {
2867 auto f = cbl_field_of(&elem);
2868 return f->level != 88;
2869 }
2870 return true;
2871 } );
2872 }
2873
2874 cbl_field_t dup = {};
2875 dup.parent = field_index(tgt);
2876 dup.line = tgt->line;
2877
2878 elem_group_t group(++bog, eog);
2879
2880 for( const auto& elem : group ) {
2881 const cbl_field_t *that(cbl_field_of(&elem));
2882 if( is_forward(that) ) {
2883 auto e = symbol_field(current_program_index(), 0, that->name);
2884 that = cbl_field_of(e); // must exist
2885 }
2886 memcpy(dup.name, that->name, sizeof(dup.name));
2887 dup.occurs = that->occurs;
2888 dup.level = that->level;
2889 switch( dup.level ) {
2890 case 0:
2891 assert(that->type == FldIndex);
2892 case 88:
2893 break;
2894 default:
2895 dup.level += tgt->level;
2896 break;
2897 }
2898 dup.parent = seek_parent(last_elem, dup.level);
2899 dup.same_as( *that, src->is_typedef() );
2900
2901 last_elem = symbol_field_add( last_elem->program, &dup );
2902 }
2903
2904 return last_elem;
2905 }
2906
2907 static bool first_among_equals( const cbl_file_t *a, const cbl_file_t *b ) {
2908 return symbol_index(symbol_elem_of(a)) < symbol_index(symbol_elem_of(b));
2909 }
2910
2911 size_t
2912 symbol_file_same_record_area( std::list<cbl_file_t*>& files ) {
2913 auto first = std::min_element(files.begin(), files.end(), first_among_equals);
2914 const auto ifirst_file = symbol_index(symbol_elem_of(*first));
2915
2916 for( auto file : files ) {
2917 if( *first == file ) {
2918 assert(symbol_index(symbol_elem_of(file)) == ifirst_file );
2919 file->same_record_as = 0;
2920 continue;
2921 }
2922 auto& redefines = cbl_field_of(symbol_at(file->default_record))->parent;
2923 redefines = (*first)->default_record;
2924 file->same_record_as = ifirst_file;
2925 }
2926 return ifirst_file;
2927 }
2928
2929 static symbol_elem_t *
2930 next_program( const symbol_elem_t *elem ) {
2931 size_t start = elem? symbol_index(elem) : 0;
2932 symbol_elem_t * e =
2933 std::find_if( symbols_begin(start), symbols_end(), is_program );
2934 if( e == symbols_end() ) {
2935 return NULL;
2936 }
2937 return e;
2938 }
2939
2940 bool
2941 is_cobol_name( const char name[] ) {
2942 for( symbol_elem_t *e = next_program(NULL);
2943 e != NULL; e = next_program(++e) ) {
2944 if( strcmp(name, cbl_label_of(e)->name) == 0 ) return true;
2945 if( symbol_field(symbol_index(e), 0, name) ) return true;
2946 if( symbol_label(symbol_index(e), LblNone, 0, name) ) return true;
2947 }
2948 return false;
2949 }
2950
2951 const char *
2952 is_numeric_constant( const char name[] ) {
2953 cbl_name_t lname;
2954 auto program = current_program_index();
2955 std::transform( name,
2956 name + std::min(sizeof(lname), strlen(name) + 1),
2957 lname, tolower );
2958 auto p = numeric_constants[program].find(lname);
2959 if( p != numeric_constants[program].end() ) {
2960 size_t isym = p->second;
2961 return cbl_field_of(symbol_at(isym))->data.initial;
2962 }
2963 return NULL;
2964 }
2965
2966 // get default record layout for a file
2967 struct cbl_field_t *
2968 symbol_file_record( const cbl_file_t *file ) {
2969 return cbl_field_of(symbol_at(file->default_record));
2970 }
2971
2972 class is_section {
2973 cbl_section_type_t section_type;
2974 public:
2975 explicit is_section( cbl_section_type_t sect ) : section_type(sect) {}
2976 bool operator()( symbol_elem_t& e ) const {
2977 return e.type == SymDataSection && cbl_section_of(&e)->type == section_type;
2978 }
2979 };
2980
2981
2982 static bool fd_record_size_cmp( const symbol_elem_t& a, const symbol_elem_t& b ) {
2983 return cbl_field_of(&a)->data.capacity < cbl_field_of(&b)->data.capacity;
2984 }
2985
2986 /*
2987 * Find largest and smallest record defined for a file. The rule is:
2988 * cbl_file_t::varies() returns true if the record size varies,
2989 * whether explicit or implied. In all cases if the record size
2990 * varies, min < else, min max == max.
2991 *
2992 * Input: Output:
2993 * ------------------------------------------ ------------------
2994 * VARIES FROM TO 1st-FD-size 2nd-FD-size varies() min max
2995 * VARIES x y true x y
2996 * VARIES x y any any true x y
2997 * VARIES x true x -1
2998 * VARIES y any any true 0 y
2999 * VARIES x 120 150 true x 150
3000 * VARIES 120 150 true 0 150
3001 * VARIES 150 true 0 150
3002 * 120 150 true 120 150
3003 * 150 false 150 150
3004 *
3005 * ISO 13.4.4.2 says "When no record description entries are specified:
3006 * a) a RECORD clause shall be specified in the file description entry"
3007 *
3008 * If VARIES TO Y is explicit, FROM 0 is implicit, notwithstanding any
3009 * record description(s).
3010 */
3011 cbl_file_t::varying_t
3012 symbol_file_record_sizes( struct cbl_file_t *file ) {
3013 if( file->varies() ) {
3014 return file->varying_size;
3015 }
3016
3017 // Compute implicit records sizes from FD 01 records
3018 assert( ! file->varying_size.explicitly );
3019
3020 auto file_element = symbol_elem_of(file);
3021 auto pend = std::find_if( file_element, symbols_end(),
3022 is_section(working_sect_e) );
3023 std::list<symbol_elem_t> records;
3024 std::copy_if( file_element, pend, back_inserter(records),
3025 [ifile = symbol_index(file_element)](const symbol_elem_t& elem) {
3026 if( elem.type == SymField ) {
3027 return ifile == cbl_field_of(&elem)->file;
3028 }
3029 return false;
3030 } );
3031 if( records.empty() ) return file->varying_size;
3032
3033 auto p = std::minmax_element(records.begin(), records.end(),
3034 fd_record_size_cmp);
3035
3036 // Make a copy, update the sizes, and return it.
3037 cbl_file_t::varying_t output = file->varying_size;
3038
3039 output.min = cbl_field_of(&*p.first)->data.capacity;
3040 output.max = cbl_field_of(&*p.second)->data.capacity;
3041
3042 assert(output.min > 0 && "min record size is 0");
3043 assert(output.min <= output.max);
3044
3045 return output;
3046 }
3047
3048 /*
3049 * Find a symbol's type based solely on its name.
3050 *
3051 * The lexer uses this function to determine if the referenced name is
3052 * special in some way. To be correct, the symbol table (or at least
3053 * the lookup mechanism) must reflect what the current namespace is.
3054 * If a symbol is ambiguous -- if a name could be a level 01 and part
3055 * of a group, say -- only the first match is returned. This may lead
3056 * the parser astray, which is too bad.
3057 *
3058 * As of 30 Oct 2021, there are 22 instances where introducing just a
3059 * plain NAME in the parser where otherwise NAME X Y is needed would
3060 * create shift-reduce conflicts. This function allows the lexer to
3061 * returns a spealized name, which the parser distinguishes from a
3062 * generic name. The S/R conflicts could in theory be resolved with
3063 * precedence, but it's not obvious to the author that's the best
3064 * choice, or the least effort.
3065 *
3066 * The risk seems small. The distinction here is by field type, not
3067 * value. If there are two fields FOO, one a level 88 and another a
3068 * variable, it's not clear if that can be resolved by the lexer, even
3069 * with the parser's help. The bet is that won't matter because
3070 * it won't happen.
3071 */
3072 enum cbl_field_type_t
3073 symbol_field_type( size_t program, const char name[] ) {
3074 struct symbol_elem_t *e = symbol_field( program, 0, name );
3075
3076 return e && e->type == SymField? cbl_field_of(e)->type: FldInvalid;
3077 }
3078
3079 struct cbl_field_t *
3080 constant_of( size_t isym )
3081 {
3082 assert(isym < symbols.nelem);
3083 struct cbl_field_t *field = cbl_field_of(symbols.elems + isym);
3084 assert((field->attr & constant_e) == constant_e);
3085 return field;
3086 }
3087
3088 bool
3089 cbl_alphabet_t::assign( const YYLTYPE& loc, unsigned char ch, unsigned char high_value ) {
3090 if( alphabet[ch] == 0xFF || alphabet[ch] == high_value) {
3091 alphabet[ch] = high_value;
3092 last_index = ch;
3093 return true;
3094 }
3095 auto taken = alphabet[ch];
3096 error_msg(loc, "ALPHABET %s, character %<%c%> (X%'%x%') "
3097 "in position %d already defined at position %d",
3098 name,
3099 ISPRINT(ch)? ch : '?', ch,
3100 high_value, taken );
3101 if( yydebug ) dump();
3102 return false;
3103 }
3104
3105 void
3106 cbl_alphabet_t::also( const YYLTYPE& loc, size_t ch ) {
3107 if( ch < 256 ) {
3108 alphabet[ch] = alphabet[last_index];
3109 if( ch == high_index ) high_index--;
3110 return;
3111 } // else it's a figurative constant ...
3112
3113 ch &= 0xFFFF; // High bit indicated symbol-table entry; mask off high word.
3114 assert( ch < 256 );
3115 auto field = cbl_field_of(symbol_at(ch));
3116 auto attr = field->attr;
3117 assert(attr & constant_e);
3118
3119 // last_index is already set; use it as the "last value before ALSO"
3120 if( attr & low_value_e ) {
3121 alphabet[0] = alphabet[last_index];
3122 return;
3123 }
3124 if( attr & high_value_e ) {
3125 alphabet[high_index--] = alphabet[last_index];
3126 return;
3127 }
3128 if( attr & (space_value_e|quote_value_e) ) {
3129 ch = field->data.initial[0];
3130 alphabet[ch] = alphabet[last_index];
3131 return;
3132 }
3133 if( attr & (zero_value_e) ) {
3134 alphabet[0] = alphabet[last_index];
3135 error_msg(loc, "ALSO value '%s' is unknown", field->name);
3136 return;
3137 }
3138 error_msg(loc, "ALSO value %zu is unknown", ch);
3139 }
3140
3141 using std::deque;
3142 static deque<cbl_field_t*> stack;
3143
3144 static cbl_field_t *
3145 new_temporary_impl( enum cbl_field_type_t type, const cbl_name_t name = nullptr )
3146 {
3147 extern int yylineno;
3148 static const struct cbl_field_t empty_alpha = {
3149 0, FldAlphanumeric, FldInvalid,
3150 intermediate_e, 0, 0, 0, nonarray, 0, "",
3151 0, cbl_field_t::linkage_t(),
3152 {MAXIMUM_ALPHA_LENGTH, MAXIMUM_ALPHA_LENGTH,
3153 0, 0, NULL}, NULL };
3154 static const struct cbl_field_t empty_float = {
3155 0, FldFloat, FldInvalid,
3156 intermediate_e,
3157 0, 0, 0, nonarray, 0, "",
3158 0, cbl_field_t::linkage_t(),
3159 {16, 16, 32, 0, NULL}, NULL };
3160 static const struct cbl_field_t empty_comp5 = {
3161 0, FldNumericBin5, FldInvalid,
3162 signable_e | intermediate_e,
3163 0, 0, 0, nonarray, 0, "",
3164 0, cbl_field_t::linkage_t(),
3165 {16, 16, MAX_FIXED_POINT_DIGITS, 0, NULL}, NULL };
3166 static const struct cbl_field_t empty_conditional = {
3167 0, FldConditional, FldInvalid, intermediate_e,
3168 0, 0, 0, nonarray, 0, "",
3169 0, cbl_field_t::linkage_t(),
3170 {}, NULL };
3171 static struct cbl_field_t empty_literal = {
3172 0, FldInvalid, FldInvalid, CONSTANT_E,
3173 0, 0, 0, nonarray, 0, "",
3174 0, cbl_field_t::linkage_t(),
3175 {}, NULL };
3176 struct cbl_field_t *f = new cbl_field_t;
3177 f->type = type;
3178
3179 switch(type) {
3180 case FldGroup:
3181 case FldAlphanumeric:
3182 *f = empty_alpha;
3183 break;
3184 case FldInvalid:
3185 case FldClass:
3186 case FldForward:
3187 case FldIndex:
3188 case FldSwitch:
3189 case FldDisplay:
3190 case FldPointer:
3191 case FldBlob:
3192 break;
3193 case FldConditional:
3194 *f = empty_conditional;
3195 break;
3196 case FldLiteralA:
3197 case FldLiteralN:
3198 *f = empty_literal;
3199 f->type = type;
3200 break;
3201 case FldNumericBin5:
3202 case FldNumericBinary:
3203 case FldNumericDisplay:
3204 case FldNumericEdited:
3205 case FldAlphaEdited:
3206 case FldPacked:
3207 *f = empty_comp5;
3208 break;
3209 case FldFloat:
3210 *f = empty_float;
3211 break;
3212 }
3213
3214 f->line = yylineno;
3215 if( is_literal(type) ) {
3216 static int nliteral = 0;
3217 snprintf(f->name, sizeof(f->name), "_literal%d",++nliteral);
3218 } else {
3219 static int nstack = 0;
3220 snprintf(f->name, sizeof(f->name), "_stack%d",++nstack);
3221 }
3222
3223 f->data.initial = name; // capture e.g. the function name
3224
3225 return f;
3226 }
3227
3228 cbl_field_t *
3229 new_temporary_decl() {
3230 auto field = new_temporary_impl(FldAlphanumeric);
3231 strcpy(field->name, "DECLARATIVES");
3232 return field;
3233 }
3234
3235 static inline cbl_field_t *
3236 parser_symbol_add2( cbl_field_t *field ) {
3237 parser_symbol_add(field);
3238 return field;
3239 }
3240
3241 static cbl_field_t *
3242 new_literal_add( const char initial[], uint32_t len, enum cbl_field_attr_t attr ) {
3243 cbl_field_t *field = NULL;
3244 if( !(attr & quoted_e) )
3245 {
3246 field = new_temporary_impl(FldLiteralN);
3247 field->attr |= attr;
3248 field->data.valify(initial);
3249 }
3250 else
3251 {
3252 static char empty[2] = "\0";
3253 field = new_temporary_impl(FldLiteralA);
3254 field->attr |= attr;
3255 field->data.initial = len > 0? initial : empty;
3256 field->data.capacity = len;
3257
3258 if( ! field->internalize() )
3259 {
3260 ERROR_FIELD(field, "inconsistent string literal encoding for '%s'", initial);
3261 }
3262 }
3263
3264 static size_t literal_count = 1;
3265 sprintf(field->name,
3266 "%s%c_" HOST_SIZE_T_PRINT_DEC,
3267 "_literal",
3268 field->type == FldLiteralA ? 'a' : 'n',
3269 (fmt_size_t)literal_count++);
3270
3271 return parser_symbol_add2(field);
3272 }
3273
3274 static temporaries_t temporaries;
3275
3276 cbl_field_t *
3277 temporaries_t::literal( const char value[], uint32_t len, cbl_field_attr_t attr ) {
3278 auto key = literal_an(value, quoted_e == (attr & quoted_e));
3279
3280 if( 0 == (attr & hex_encoded_e) ) {
3281 auto p = literals.find(key);
3282 if( p != literals.end() ) {
3283 cbl_field_t *field = p->second;
3284 return field;
3285 }
3286 }
3287 return literals[key] = new_literal_add(value, len, attr);
3288 }
3289
3290 cbl_field_t *
3291 new_literal( uint32_t len, const char initial[], enum cbl_field_attr_t attr ) {
3292 return temporaries.literal(initial, len, attr);
3293 }
3294
3295 void
3296 temporaries_t::dump() const {
3297 extern int yylineno;
3298 char *output = xasprintf("%4d: " HOST_SIZE_T_PRINT_UNSIGNED " Literals",
3299 yylineno, (fmt_size_t)literals.size());
3300
3301 for( const auto& elem : used ) {
3302 if( ! elem.second.empty() ) {
3303 char *so_far = output;
3304 output = xasprintf("%s, " HOST_SIZE_T_PRINT_UNSIGNED " %s",
3305 so_far,
3306 (fmt_size_t)elem.second.size(),
3307 3 + cbl_field_type_str(elem.first));
3308 free(so_far);
3309 }
3310 }
3311 dbgmsg("status: %s", output);
3312 free(output);
3313 }
3314
3315 temporaries_t::~temporaries_t() {
3316 }
3317
3318 cbl_field_t *
3319 temporaries_t::add( cbl_field_t *field ) {
3320 auto p = used[field->type].insert(field);
3321 bool yn(p.second);
3322 assert(yn);
3323 return *p.first;
3324 };
3325
3326 cbl_field_t *
3327 temporaries_t::reuse( cbl_field_type_t type ) {
3328 //// DUBNER is defeating reuse as part of investigating problems with recursion
3329 return NULL;
3330 ////
3331
3332 auto& fields = freed[type];
3333 cbl_field_t *field;
3334
3335 if( fields.empty() ) {
3336 return NULL;
3337 } else {
3338 auto p = fields.begin();
3339 field = *p;
3340 fields.erase(p);
3341 }
3342
3343 return add(field);
3344 }
3345
3346 cbl_field_t *
3347 temporaries_t::acquire( cbl_field_type_t type, const cbl_name_t name ) {
3348 cbl_field_t *field = reuse(type);
3349
3350 if( !field ) {
3351 field = new_temporary_impl(type, name);
3352 add(field);
3353 }
3354 return parser_symbol_add2(field); // notify of reuse
3355 }
3356
3357 void
3358 symbol_temporaries_free() {
3359 for( auto& elem : temporaries.used ) {
3360 const cbl_field_type_t& type(elem.first);
3361 temporaries_t::fieldset_t& used(elem.second);
3362
3363 auto freed = std::inserter(temporaries.freed[type],
3364 temporaries.freed[type].begin());
3365 std::transform( used.begin(), used.end(), freed,
3366 []( auto field ) {
3367 switch( field->type ) {
3368 case FldConditional:
3369 field->attr &= intermediate_e;
3370 break;
3371 case FldNumericBin5:
3372 field->set_attr(signable_e);
3373 break;
3374 default:
3375 break;
3376 }
3377 return field;
3378 } );
3379 used.clear();
3380 }
3381 }
3382
3383 cbl_field_t *
3384 new_alphanumeric( size_t capacity, const cbl_name_t name = nullptr ) {
3385 cbl_field_t * field = new_temporary_impl(FldAlphanumeric, name);
3386 field->data.capacity = capacity;
3387 temporaries.add(field);
3388 return parser_symbol_add2(field);
3389 }
3390
3391 cbl_field_t *
3392 new_temporary( enum cbl_field_type_t type, const char *initial ) {
3393 if( ! initial ) {
3394 assert( ! is_literal(type) ); // Literal type must have literal value.
3395 return temporaries.acquire(type, initial);
3396 }
3397 if( is_literal(type) ) {
3398 auto field = temporaries.literal(initial,
3399 type == FldLiteralA? quoted_e : none_e);
3400 return field;
3401 }
3402 cbl_field_t *field = new_temporary_impl(type, initial);
3403 temporaries.add(field);
3404 parser_symbol_add(field);
3405
3406 return field;
3407 }
3408
3409 #if needed
3410 cbl_field_t *
3411 keep_temporary( cbl_field_type_t type ) {
3412 auto field = new_temporary(type);
3413 bool ok = temporaries.keep(field);
3414 assert(ok);
3415 return field;
3416 }
3417 #endif
3418
3419 cbl_field_t *
3420 new_temporary_like( cbl_field_t skel ) {
3421 auto field = temporaries.reuse(skel.type);
3422 if( ! field ) {
3423 field = new_temporary_impl(skel.type);
3424 temporaries.add(field);
3425 }
3426 memcpy(skel.name, field->name, sizeof(field->name));
3427 skel.var_decl_node = field->var_decl_node;
3428 *field = skel;
3429
3430 return parser_symbol_add2(field);
3431 }
3432
3433 cbl_field_t *
3434 new_temporary_clone( const cbl_field_t *orig) {
3435 cbl_field_type_t type = is_literal(orig)? FldAlphanumeric : orig->type;
3436 auto field = temporaries.reuse(type);
3437 if( ! field ) {
3438 field = new_temporary_impl(type);
3439 temporaries.add(field);
3440 }
3441 field->data = orig->data;
3442 if( field->type == FldNumericBin5 ) field->type = orig->type;
3443 field->attr = intermediate_e;
3444
3445 return parser_symbol_add2(field);
3446 }
3447
3448 bool
3449 cbl_field_t::is_ascii() const {
3450 return std::all_of( data.initial,
3451 data.initial + data.capacity,
3452 isascii );
3453 }
3454
3455 /*
3456 * Convert an input source-code string literal (or VALUE) to internal encoding.
3457 *
3458 * Input encoding initially defaults to UTF-8, regardless of locale(7),
3459 * for two reasons:
3460 * 1) The source code might not match the locale
3461 * 2) The assumption is easily disproved with most input. That is,
3462 * input values above 0x7F will rarely look like UFT-8 unless
3463 * they actually are UTF-8.
3464 *
3465 * If conversion from UTF-8 fails, the compiler's locale is examined
3466 * next. If it is C, it is ignored, else it is tried. If that fails,
3467 * the input is assumed to be encoded as CP1252.
3468 *
3469 * This is a global static sticky setting, meaning that during
3470 * compilation, if it moves off the default, it adjusts only once, and
3471 * never reverts.
3472 */
3473 static const char standard_internal[] = "CP1252";
3474 extern os_locale_t os_locale;
3475
3476 static const char *
3477 guess_encoding() {
3478 static const char *fromcode;
3479
3480 if( ! fromcode ) {
3481 return fromcode = os_locale.assumed;
3482 }
3483
3484 if( fromcode == os_locale.assumed ) {
3485 fromcode = os_locale.codeset;
3486 if( 0 != strcmp(fromcode, "C") ) { // anything but that
3487 return fromcode;
3488 }
3489 }
3490
3491 return standard_internal;
3492 }
3493
3494 const char *
3495 cbl_field_t::internalize() {
3496 static const char *tocode = standard_internal;
3497 static const char *fromcode = guess_encoding();
3498 static iconv_t cd = iconv_open(tocode, fromcode);
3499 static const size_t noconv = size_t(-1);
3500
3501 if (cd == (iconv_t)-1) {
3502 yywarn("failed %<iconv_open%> tocode = %<%s%> fromcode = %s", tocode, fromcode);
3503 }
3504
3505 bool using_assumed = fromcode == os_locale.assumed;
3506
3507 if( fromcode == tocode || has_attr(hex_encoded_e) ) {
3508 return data.initial;
3509 }
3510
3511 if( is_ascii() ) return data.initial;
3512 assert(data.capacity > 0);
3513
3514 std::vector<char> output(data.capacity + 2, '\0');
3515 char *out = output.data();
3516 char *in = const_cast<char*>(data.initial);
3517 size_t n, inbytesleft = data.capacity, outbytesleft = output.size();
3518 if( !is_literal(this) && inbytesleft < strlen(data.initial) ) {
3519 inbytesleft = strlen(data.initial);
3520 }
3521
3522 assert(fromcode != tocode);
3523
3524 while( (n = iconv( cd, &in, &inbytesleft, &out, &outbytesleft)) == noconv ) {
3525 if( !using_assumed ) break; // change only once
3526 fromcode = guess_encoding();
3527 cd = iconv_open(tocode, fromcode);
3528 dbgmsg("%s: trying input encoding %s", __func__, fromcode);
3529 if( fromcode == tocode ) break;
3530 }
3531
3532 if( n == noconv ) {
3533 if( !using_assumed ) {
3534 yywarn("failed to decode '%s' as %s", data.initial, fromcode);
3535 return NULL;
3536 }
3537 return data.initial;
3538 }
3539
3540 if( 0 < inbytesleft ) {
3541 // data.capacity + inbytesleft is not correct if the remaining portion has
3542 // multibyte characters. But the fact reamins that the VALUE is too big.
3543 ERROR_FIELD(this, "%s %s VALUE '%s' requires %zu bytes for size %u",
3544 cbl_field_t::level_str(level), name, data.initial,
3545 data.capacity + inbytesleft, data.capacity );
3546 }
3547
3548 // Replace data.initial only if iconv output differs.
3549 if( 0 != memcmp(data.initial, output.data(), out - output.data()) ) {
3550 assert(out <= output.data() + data.capacity);
3551
3552 dbgmsg("%s: converted '%.*s' to %s",
3553 __func__, data.capacity, data.initial, tocode);
3554
3555 int len = int(out - output.data());
3556 char *mem = static_cast<char*>( xcalloc(1, output.size()) );
3557
3558 // Set the new memory to all blanks, tacking a '!' on the end.
3559 memset(mem, 0x20, output.size() - 1);
3560 mem[ output.size() - 2] = '!';
3561
3562 if( is_literal(this) ) {
3563 data.capacity = len; // trailing '!' will be overwritten
3564 }
3565
3566 memcpy(mem, output.data(), len); // copy only as much as iconv converted
3567
3568 free(const_cast<char*>(data.initial));
3569 data.initial = mem;
3570 }
3571
3572 return data.initial;
3573 }
3574
3575 const char *
3576 cbl_label_t::str() const {
3577 char *buf;
3578 switch(type) {
3579 case LblParagraph:
3580 buf = xasprintf("%-12s %s OF '%s', line %d", type_str() + 3, name,
3581 parent? cbl_label_of(symbol_at(parent))->name : "", line);
3582 break;
3583 case LblProgram:
3584 if( parent == 0 ) {
3585 buf = xasprintf("%-12s %s top level [%s], line %d",
3586 type_str() + 3, name, mangled_name, line);
3587 } else {
3588 buf = xasprintf("%-12s %s OF #" HOST_SIZE_T_PRINT_UNSIGNED " '%s' [%s], line %d",
3589 type_str() + 3, name, (fmt_size_t)parent,
3590 cbl_label_of(symbol_at(parent))->name,
3591 mangled_name, line);
3592 }
3593 break;
3594 default:
3595 buf = xasprintf("%-12s %s, line %d", type_str() + 3, name, line);
3596 }
3597 return buf;
3598 }
3599
3600 size_t
3601 cbl_label_t::explicit_parent() const {
3602 switch(type) {
3603 case LblParagraph: case LblSection: case LblNone:
3604 if( parent != 0 ) {
3605 // implicit parents don't count
3606 symbol_elem_t *p = symbol_at(parent);
3607 if( p->type == SymLabel && cbl_label_of(p)->name[0] == '_' ) {
3608 return 0;
3609 }
3610 }
3611 break;
3612 default:
3613 break;
3614 }
3615 return parent;
3616 }
3617
3618 cbl_prog_hier_t::cbl_prog_hier_t() {
3619 std::copy_if( symbols_begin(), symbols_end(),
3620 std::back_inserter(labels), is_program );
3621 assert(! labels.empty());
3622 }
3623
3624 /*
3625 * Map of program to its callable COMMON programs.
3626 */
3627 static std::map<size_t, symbolset_t> common_callables;
3628
3629 symbolset_t
3630 symbol_program_programs() {
3631 symbolset_t programs;
3632
3633 for( const auto& elem : common_callables ) {
3634 if( elem.first == 0 ) continue;
3635 assert(symbol_at(elem.first)->type == SymLabel);
3636 assert(is_program(*symbol_at(elem.first))); // might be a function
3637 programs.insert(elem.first);
3638 }
3639 return programs;
3640 }
3641
3642 static void
3643 common_callables_update( const size_t iprog ) {
3644 // Add this directly contained COMMON program to the parent's set.
3645 auto prog = cbl_label_of(symbol_at(iprog));
3646 if( prog->type != LblProgram ) return;
3647 if( prog->common ) {
3648 common_callables[prog->parent].insert(iprog);
3649 }
3650
3651 // Add all ancestors' COMMON programs to the iprog siblings and uncles.
3652 std::list<size_t> dnr; // do not recurse
3653
3654 while( prog->parent > 0 ) {
3655 if( !prog->recursive ) dnr.push_back(symbol_index(symbol_elem_of(prog)));
3656 auto c = common_callables[prog->parent];
3657 common_callables[iprog].insert(c.begin(), c.end());
3658 prog = cbl_label_of(symbol_at(prog->parent));
3659 }
3660 // Top-level programs (parent == 0) cannot be COMMON, but are public
3661 // symbols. They can be called from anywhere, except from a
3662 // (directly or indirectly) contained program, unless marked
3663 // RECURSIVE.
3664 assert(prog->parent == 0);
3665 auto itop = symbol_index(symbol_elem_of(prog));
3666 common_callables[0].insert(itop);
3667 if( prog->recursive ) {
3668 common_callables[iprog].insert(itop);
3669 }
3670
3671 for( size_t isym : dnr ) {
3672 common_callables[iprog].erase(isym);
3673 }
3674 }
3675
3676 /*
3677 * Unlike fields, there is no LblForward. Instead, a forward
3678 * reference to a procedure -- section or paragraph name -- begins
3679 * life as LblNone. When it is actually defined, the lookup function
3680 * updates the LblNone entry and defines its type, parent, and line
3681 * number.
3682 */
3683 cbl_label_t *
3684 symbol_label_add( size_t program, cbl_label_t *input )
3685 {
3686 cbl_label_t *label = symbol_label(program, input->type,
3687 input->parent, input->name);
3688
3689 if( label && label->type == LblNone ) {
3690 label->type = input->type;
3691 label->parent = input->parent;
3692 label->line = input->line;
3693
3694 return label;
3695 }
3696
3697 // Set the program's mangled name, dehyphenated and uniqified by parent index.
3698 if( input->type == LblProgram ) {
3699 char *psz = cobol_name_mangler(input->name);
3700 input->mangled_name = xasprintf("%s." HOST_SIZE_T_PRINT_UNSIGNED,
3701 psz, (fmt_size_t)input->parent);
3702 free(psz);
3703 }
3704
3705 struct symbol_elem_t
3706 elem { program, *input }, *e = &elem;
3707
3708 assert(0 <= e->elem.label.line);
3709 e->elem.label.line = -e->elem.label.line; // force insertion
3710
3711 if( (e = symbol_add(&elem)) == NULL ) {
3712 cbl_errx("%s:%d: could not add '%s'", __func__, __LINE__, label->name);
3713 }
3714 assert(e);
3715
3716 common_callables_update( symbol_index(e) );
3717
3718 // restore munged line number unless symbol_add returned an existing label
3719 if( e->elem.label.line < 0 ) e->elem.label.line = -e->elem.label.line;
3720
3721 symbols.labelmap_add(e);
3722 return cbl_label_of(e);
3723 }
3724
3725 /*
3726 * Under ISO (and not IBM) Declaratives are followed by a Section name. If
3727 * Declaratives were used, when the first statement is parsed verify that it
3728 * was preceeded by a Section name.
3729 */
3730 bool
3731 symbol_label_section_exists( size_t eval_label_index ) {
3732 auto eval = symbols_begin(eval_label_index);
3733 /* cppcheck warns that the following statement depends on the order of
3734 evaluation of side effects. Since this isn't my code, and since I don't
3735 think the warning can be eliminated without rewriting it, I am just
3736 supprressing it.
3737 -- Bob Dubner, 2025-07-14 */
3738 // cppcheck-suppress unknownEvaluationOrder
3739 bool has_section = std::any_of( ++eval, symbols_end(),
3740 [program = eval->program]( const auto& sym ) {
3741 if( program == sym.program && sym.type == SymLabel ) {
3742 const auto& L(sym.elem.label);
3743 // true if the symbol is an explicit label.
3744 return L.type == LblSection && L.name[0] != '_';
3745 }
3746 return false;
3747 } );
3748 if( yydebug && ! has_section ) {
3749 symbols_dump(eval_label_index, true);
3750 }
3751 // Return true if a user-defined SECTION was found after the Declaratives
3752 // label section.
3753 return has_section;
3754 }
3755
3756 cbl_label_t *
3757 symbol_program_add( size_t program, cbl_label_t *input )
3758 {
3759 symbol_elem_t elem { program, *input }, *e;
3760
3761 assert( is_program(elem) );
3762
3763 // Set the program's mangled name, dehyphenated and uniqified by parent index.
3764 char *psz = cobol_name_mangler(input->name);
3765 elem.elem.label.mangled_name = xasprintf("%s." HOST_SIZE_T_PRINT_UNSIGNED,
3766 psz, (fmt_size_t)input->parent);
3767 free(psz);
3768
3769 e = std::find_if( symbols_begin(program), symbols_end(),
3770 [program, name = input->name]( const auto& elem ) {
3771 if( elem.type == SymLabel ) {
3772 if( program == elem.program ) {
3773 auto L = cbl_label_of(&elem);
3774 if( 0 == strcasecmp(name, L->name) ) return true;
3775 }
3776 }
3777 return false;
3778 } );
3779 if( e != symbols_end() ) return NULL;
3780
3781 e = symbol_append(elem);
3782
3783 common_callables_update( symbol_index(e) );
3784
3785 return cbl_label_of(e);
3786 }
3787
3788 #if 1
3789 struct cbl_special_name_t *
3790 symbol_special( special_name_t id ) {
3791 cbl_special_name_t special = { 0, id };
3792 struct symbol_elem_t key { 0, special }, *e;
3793
3794 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
3795 &symbols.nelem, sizeof(key),
3796 symbol_elem_cmp ) );
3797 return e? cbl_special_name_of(e) : NULL;
3798 }
3799 #endif
3800
3801 struct symbol_elem_t *
3802 symbol_special_add( size_t program, struct cbl_special_name_t *special )
3803 {
3804 // Ensure this special name isn't already defined for this program.
3805 struct symbol_elem_t *e = symbol_special(program, special->name);
3806
3807 if( e ) {
3808 return e;
3809 }
3810 assert(e == NULL);
3811
3812 struct symbol_elem_t elem { program, *special };
3813
3814 if( (e = symbol_add(&elem)) == NULL ) {
3815 cbl_errx( "%s:%d: could not add '%s'", __func__, __LINE__, special->name);
3816 }
3817
3818 elem_key_t key(program, cbl_special_name_of(e)->name);
3819 symbols.specials[key] = symbol_index(e);
3820
3821 return e;
3822 }
3823
3824 struct cbl_section_t *
3825 symbol_section( size_t program, struct cbl_section_t *section ) {
3826 struct symbol_elem_t key { program, *section }, *e;
3827
3828 e = static_cast<struct symbol_elem_t *>(lfind( &key, symbols.elems,
3829 &symbols.nelem, sizeof(key),
3830 symbol_elem_cmp ) );
3831 return e? cbl_section_of(e) : NULL;
3832 }
3833
3834
3835 struct symbol_elem_t *
3836 symbol_section_add( size_t program, struct cbl_section_t *section )
3837 {
3838 if( symbol_section(program, section) ) {
3839 return NULL; // error, exists
3840 }
3841
3842 struct symbol_elem_t *e, elem { program, *section };
3843
3844 if( (e = symbol_add(&elem)) == NULL ) {
3845 cbl_errx( "%s:%d: could not add '%s'", __func__, __LINE__, section->name());
3846 }
3847
3848 return e;
3849 }
3850
3851 static int
3852 currency_char_in_string(const char *picture) {
3853 // This can take an unexpanded string
3854 int retval = 0;
3855 while(*picture) {
3856 if( symbol_currency(*picture) ){
3857 retval = *picture;
3858 break;
3859 }
3860 picture += 1;
3861 }
3862 return retval;
3863 }
3864
3865 static
3866 int l_and_r(const char *expanded_picture, int ch) {
3867 const char *l = strchr(expanded_picture, ch);
3868 const char *r = strrchr(expanded_picture, ch);
3869 return r > l ? ch : 0;
3870 }
3871
3872 static int
3873 floating_char_in_string(const char *expanded_picture) {
3874 int ch = '+';
3875 if( l_and_r(expanded_picture, ch) ) {
3876 return ch;
3877 }
3878 ch = '-';
3879 if( l_and_r(expanded_picture, ch) ) {
3880 return ch;
3881 }
3882 ch = currency_char_in_string(expanded_picture);
3883 if( ch && l_and_r(expanded_picture, ch) ) {
3884 return ch;
3885 }
3886 return 0;
3887 }
3888
3889 char *
3890 expand_picture(const char *picture)
3891 {
3892 assert(strlen(picture) < PICTURE_MAX); // guaranteed by picset() in scanner
3893 size_t retval_length = PICTURE_MAX;
3894 char *retval = static_cast<char *>(xmalloc(retval_length));
3895 size_t index = 0;
3896
3897 int ch;
3898 int prior_ch = '\0';
3899 const char *p = picture;
3900
3901 long repeat;
3902
3903 int currency_symbol = currency_char_in_string(picture);
3904
3905 while( (ch = (*p++ & 0xFF) ) )
3906 {
3907 if( ch == '(' )
3908 {
3909 // Pick up the number after the left parenthesis
3910 char *endchar;
3911 repeat = strtol(p, &endchar, 10);
3912
3913 // We subtract one because we know that the character just before
3914 // the parenthesis was already placed in dest
3915 repeat -= 1;
3916
3917 // Update p to the character after the right parenthesis
3918 p = endchar + 1;
3919
3920 if( index + repeat >= retval_length )
3921 {
3922 retval_length <<= 1;
3923 retval = static_cast<char *>(xrealloc(retval, retval_length));
3924 }
3925
3926 while(repeat--)
3927 {
3928 retval[index++] = prior_ch;
3929 }
3930 }
3931 else
3932 {
3933 if( index >= retval_length )
3934 {
3935 retval_length <<= 1;
3936 retval = static_cast<char *>(xrealloc(retval, retval_length));
3937 }
3938 retval[index++] = ch;
3939 }
3940 prior_ch = ch;
3941 }
3942 if( index >= retval_length )
3943 {
3944 retval_length <<= 1;
3945 retval = static_cast<char *>(xrealloc(retval, retval_length));
3946 }
3947 retval[index++] = '\0';
3948
3949 size_t dest_length = strlen(retval);
3950
3951 // We have to take into account the possibility that the currency symbol
3952 // mapping might be to a string of more than one character:
3953
3954 if( currency_symbol )
3955 {
3956 size_t sign_length = strlen(symbol_currency(currency_symbol)) - 1;
3957 if( sign_length )
3958 {
3959 char *pcurrency = strchr(retval, currency_symbol);
3960 assert(pcurrency);
3961 memmove( pcurrency + sign_length,
3962 pcurrency,
3963 dest_length+1 - (pcurrency-retval));
3964 for(size_t i=0; i<sign_length; i++)
3965 {
3966 pcurrency[i] = 'B';
3967 }
3968 }
3969 }
3970
3971 return retval;
3972 }
3973
3974 int
3975 length_of_picture(const char *picture)
3976 {
3977 // Calculate the length of a PICTURE string with the parenthetical
3978 // abbreviations expanded: +9(10).9(4)CR, as an example, returns 18
3979 int retval = 0;
3980 char ch;
3981 char prior_char = 0; // Calm the compiler down
3982 const char *p = picture;
3983 const char *currency_sign = NULL;
3984 int currency_char = currency_char_in_string(picture);
3985
3986 if( currency_char )
3987 {
3988 currency_sign = symbol_currency(currency_char);
3989 }
3990
3991 while( (ch = *p++) ) {
3992 if( ch == '(' ) {
3993 // Pick up the number that starts after the left parenthesis
3994 char *endchar;
3995 int increment = strtol(p, &endchar, 10);
3996 if( prior_char != 'P' ) {
3997 retval += increment-1 ;
3998 }
3999 p = endchar + 1;
4000 }
4001 else {
4002 prior_char = TOUPPER(ch);
4003 if( prior_char != 'P' ) {
4004 // P-scaling characters don't count in the capacity:
4005 retval += 1;
4006 }
4007 }
4008
4009 }
4010 // We need to adjust for the length of a currency sign, because it might
4011 // have more than one character. We've already accounted for one of its
4012 // characters, so....
4013 if( currency_sign ) {
4014 retval += strlen(currency_sign) - 1;
4015 }
4016 return retval;
4017 }
4018
4019 int
4020 digits_of_picture(const char *runlength_picture, bool return_rdigits)
4021 {
4022 // This is a strangely busy routine. The capacity is calculated elsewhere,
4023 // by the length_of_picture() routine. This routine calculates the
4024 // total number of digits (which are the total number of digit positions)
4025 // and the number of rdigits (digit positions to the right of any decimal
4026 // point.)
4027 //
4028 // It also takes into account the possibility of the number being P-scaled.
4029 // The scaled_e attribute also gets set separately. For a numeric-edited
4030 // scaled_e value, a positive value of rdigits means the number is less than
4031 // 1.000000 and has an extra rdigits's count of '0' between the decimal
4032 // point and the rest of the number
4033 //
4034 // A negative value of rdigits means that the number has no decimal places,
4035 // is zero or greater, and has an extra scaling factor of 10^(-rdigits)
4036
4037 int retval;
4038 char *picture = expand_picture(runlength_picture);
4039 int digits = 0;
4040 int rdigits = 0;
4041 int pcount = 0;
4042 unsigned char ch;
4043 const char *p = picture;
4044 const char *rightmost_p = NULL;
4045 const char *rightmost_d = NULL;
4046 const char *decimal_position = NULL;
4047 const char *first_float = NULL;
4048
4049 unsigned char floating_character = floating_char_in_string(picture);
4050
4051 while( (ch = *p++) )
4052 {
4053 if( ch == decimal_point || ch == 'v' || ch == 'V')
4054 {
4055 // This is an actual or virtual decimal point
4056 // There should only be one of these in the picture string
4057 decimal_position = p-1;
4058 }
4059 else if( ch == floating_character )
4060 {
4061 // All but the first floating character acts like a digit
4062 // position. We'll adjust the counts at the end
4063 digits += 1;
4064 if( decimal_position )
4065 {
4066 // Having encountered a decimal point means this is an
4067 // rdigit:
4068 rdigits += 1;
4069 }
4070 if( !first_float )
4071 {
4072 first_float = p-1;
4073 }
4074 continue;
4075 }
4076 else
4077 {
4078 switch(ch)
4079 {
4080 case '9' :
4081 case 'z' :
4082 case 'Z' :
4083 case '*' :
4084 // These are positions that can hold a digit
4085 rightmost_d = p-1;
4086 digits += 1;
4087 if( decimal_position )
4088 {
4089 // Having encountered a decimal point means this is an
4090 // rdigit:
4091 rdigits += 1;
4092 }
4093 break;
4094
4095 case 'P':
4096 case 'p':
4097 rightmost_p = p-1;
4098 pcount += 1;
4099 break;
4100 }
4101 }
4102 }
4103
4104 // We have looped through all the characters
4105
4106 if( floating_character )
4107 {
4108 // Account for the fact that ++ turns into +<digit>, but only one digit
4109 digits -= 1;
4110
4111 if( decimal_position )
4112 {
4113 if( first_float > decimal_position )
4114 {
4115 // Because the first_float is to the right of the
4116 // decimal point, rdigits has to be reduced by one:
4117 rdigits -=1 ;
4118 }
4119 }
4120 }
4121
4122 if( pcount )
4123 {
4124 // We encountered some P-scaling characters in the PICTURE string.
4125 if( rightmost_p < rightmost_d )
4126 {
4127 // This is a scaled variable of type PPP999
4128 rdigits = pcount;
4129 }
4130 else
4131 {
4132 // This is a scaled variable of type 999PPP
4133 rdigits = -pcount;
4134 }
4135 }
4136
4137 free(picture);
4138
4139 if(return_rdigits)
4140 {
4141 retval = rdigits;
4142 }
4143 else
4144 {
4145 retval = digits;
4146 }
4147
4148 return retval;
4149 }
4150
4151
4152 int
4153 rdigits_of_picture(const char *picture) {
4154 return digits_of_picture(picture, true);
4155 }
4156
4157 bool
4158 is_picture_scaled(const char *picture) {
4159 bool retval = false;
4160 if( strchr( picture, 'P') ) {
4161 retval = true;
4162 }
4163 if( strchr( picture, 'p') ) {
4164 retval = true;
4165 }
4166 return retval;
4167 }
4168
4169 /*
4170 * Static call support. Return reachable programs.
4171 *
4172 * 8.4.5.2 Scope of program-names
4173 *
4174 * "The names assigned to programs that are contained directly or
4175 * indirectly within the same outermost program shall be unique within
4176 * that outermost program."
4177 *
4178 * At point of CALL, the target name might or might not be that of a
4179 * contained or COMMON program. If no such program exists, the CALL
4180 * is to an external reference. If exactly one such program exists,
4181 * the CALL references that program. The returned map is used to
4182 * enforce those rules, and to replace seemingly external calls with
4183 * internal ones.
4184 */
4185
4186 symbolset_t
4187 symbol_program_callables( size_t program ) {
4188 symbolset_t callables = common_callables[program];
4189
4190 auto self = cbl_label_of(symbol_at(program));
4191 auto start_with = 0 < self->parent? self->parent : program;
4192
4193 // Build a list of programs reachable by the current program.
4194 for( auto e = symbols_begin(++start_with); e < symbols_end(); e++ ) {
4195 if( e->type != SymLabel ) continue;
4196 if( e->elem.label.type != LblProgram ) continue;
4197
4198 const cbl_label_t * prog = cbl_label_of(e);
4199 if( program == symbol_index(e) && !prog->recursive ) continue;
4200
4201 if( (self->parent == prog->parent && prog->common) ||
4202 (prog->parent == program) )
4203 {
4204 callables.insert(symbol_index(e));
4205 }
4206 }
4207
4208 return callables;
4209 }
4210
4211
4212 const cbl_label_t *
4213 symbol_program_local( const char tgt_name[] ) {
4214 symbolset_t callables = symbol_program_callables(current_program_index());
4215
4216 for( auto callable : callables ) {
4217 auto called = cbl_label_of(symbol_at(callable));
4218 if( 0 == strcasecmp(called->name, tgt_name) ) return called;
4219 }
4220 return NULL;
4221 }
4222
4223 /*
4224 * FILE SECTION support
4225 */
4226
4227 /*
4228 * SPECIAL-NAMES support
4229 */
4230 std::map<char, const char *> currencies;
4231
4232 // cppcheck-suppress-begin [nullPointerRedundantCheck]
4233 bool
4234 symbol_currency_add( const char symbol[], const char sign[] ) {
4235 // In service of CURRENCY sign PICTURE SYMBOL symbol
4236 // The single-character 'symbol' is replaced with multi-char 'sign'
4237 // by the NumericEdited processing.
4238 if( !symbol ) {
4239 symbol = xasprintf("%c", *sign);
4240 }
4241 currencies[*symbol] = sign;
4242 return true;
4243 }
4244 // cppcheck-suppress-end [nullPointerRedundantCheck]
4245
4246 const char *
4247 symbol_currency( char sign ) {
4248 // We need a default of '$'
4249 if( currencies.size() == 0 ) {
4250 currencies['$'] = "$";
4251 }
4252 if( sign == '\0' ) { // default
4253 auto result = currencies.begin();
4254 gcc_assert(result != currencies.end());
4255 return result->second;
4256 }
4257 auto result = currencies.find(sign);
4258 return result == currencies.end()? NULL : result->second;
4259 }
4260
4261 char symbol_decimal_point_set( char ch ) { return decimal_point = ch; }
4262 char symbol_decimal_point() { return decimal_point; }
4263 bool decimal_is_comma() { return decimal_point == ','; }
4264
4265 /*
4266 * OCCURS support
4267 */
4268
4269 /*
4270 * A cbl_occurs_key_t is part of a field definition, and comprises
4271 * size_t symbol indexes. A cbl_key_t is a list of field pointers,
4272 * and can be created ad hoc to describe a sort. We construct a
4273 * cbl_key_t from cbl_occurs_key_t.
4274 */
4275 cbl_key_t::
4276 cbl_key_t( const cbl_occurs_key_t& that )
4277 : ascending(that.ascending)
4278 {
4279 std::transform( that.field_list.fields,
4280 that.field_list.fields + that.field_list.nfield,
4281 std::back_inserter(fields),
4282 []( size_t isym ) {
4283 return cbl_field_of(symbol_at(isym));
4284 } );
4285 }
4286
4287 void
4288 cbl_occurs_t::key_alloc( bool ascending ) {
4289 auto nbytes = sizeof(keys[0]) * (nkey + 1);
4290 cbl_occurs_key_t key = { ascending, cbl_field_list_t() };
4291
4292 keys = static_cast<cbl_occurs_key_t *>(xrealloc(keys, nbytes));
4293 keys[nkey++] = key;
4294 }
4295
4296 void
4297 cbl_occurs_t::field_add( cbl_field_list_t& field_list, const cbl_field_t *field ) {
4298 cbl_field_list_t list = field_list;
4299 size_t ifield = field_index(field);
4300 auto nbytes = sizeof(list.fields[0]) * (list.nfield + 1);
4301
4302 list.fields = static_cast<size_t*>(xrealloc(list.fields, nbytes));
4303 list.fields[list.nfield++] = ifield;
4304 field_list = list;
4305 }
4306
4307 void
4308 cbl_occurs_t::key_field_add( cbl_field_t *field ) {
4309 assert(nkey > 0);
4310 cbl_occurs_key_t& key = keys[nkey-1];
4311 field_add(key.field_list, field);
4312 }
4313
4314 void
4315 cbl_occurs_t::index_add( const cbl_field_t *field ) {
4316 field_add(indexes, field);
4317 }
4318
4319 class is_field_at {
4320 cbl_field_t *field;
4321 public:
4322 explicit is_field_at( cbl_field_t *field ) : field(field) {}
4323 bool operator()( size_t isym ) const {
4324 return field == field_at(isym);
4325 }
4326 };
4327
4328 cbl_occurs_key_t *
4329 cbl_occurs_t::key_of( cbl_field_t *field ) {
4330 for( auto key = keys; key < keys + nkey; key++ ) {
4331 size_t *fields = key->field_list.fields;
4332 size_t *efield = key->field_list.fields + key->field_list.nfield;
4333 auto f = std::find_if( fields, efield, is_field_at(field) );
4334 if( f < efield ) {
4335 return key;
4336 }
4337 }
4338 return NULL;
4339 }
4340
4341 bool
4342 cbl_occurs_t::subscript_ok( const cbl_field_t *subscript ) const {
4343 if( !is_literal(subscript) ) {
4344 return true; // Cannot check non-literals, so, OK.
4345 }
4346 // It must be a number.
4347 if( subscript->type != FldLiteralN ) return false;
4348
4349 // This only gets us int64_t, which is more than adequate for a table subscript
4350 auto sub = real_to_integer (TREE_REAL_CST_PTR (subscript->data.value_of()));
4351 REAL_VALUE_TYPE csub;
4352 real_from_integer (&csub, VOIDmode, sub, SIGNED);
4353
4354 if( sub < 1
4355 || !real_identical (&csub,
4356 TREE_REAL_CST_PTR (subscript->data.value_of())) ) {
4357 return false; // zero/fraction invalid
4358 }
4359 if( bounds.fixed_size() ) {
4360 return (size_t)sub <= bounds.upper;
4361 }
4362 return bounds.lower <= (size_t)sub && (size_t)sub <= bounds.upper;
4363 }
4364
4365 const cbl_field_t *
4366 symbol_unresolved_file_key( const cbl_file_t * file,
4367 const cbl_name_t key_field_name ) {
4368 const symbol_elem_t *file_sym = symbol_elem_of(file);
4369 size_t program = file_sym->program;
4370 for( const symbol_elem_t *e = file_sym - 1; e->program == program; e-- ) {
4371 if( e->type == SymFile ) break;
4372 if( e->type == SymField ) {
4373 auto f = cbl_field_of(e);
4374 if( f->type == FldLiteralA ) break;
4375 if( f->type == FldForward ) {
4376 if( 0 == strcmp(key_field_name, f->name) ) {
4377 return f;
4378 }
4379 }
4380 }
4381 }
4382 return nullptr;
4383 }
4384
4385 cbl_file_key_t::
4386 cbl_file_key_t( cbl_name_t name,
4387 const std::list<cbl_field_t *>& fields,
4388 bool is_unique )
4389 : unique(is_unique)
4390 , leftmost(0)
4391 {
4392 assert(name);
4393 memcpy(this->name, name, sizeof(this->name));
4394 nfield = fields.size();
4395 assert(nfield > 0);
4396 this->fields = new size_t[nfield];
4397 std::transform( fields.begin(), fields.end(), this->fields, field_index );
4398 }
4399
4400 size_t cbl_file_key_t::
4401 offset() const {
4402 return cbl_field_of(symbol_at(fields[0]))->offset;
4403 }
4404
4405 /*
4406 * A multi-field key has a name. A single-field key has no name.
4407 */
4408 bool cbl_file_key_t::
4409 operator==( const cbl_field_t *key_field ) {
4410 this->leftmost = 0;
4411
4412 // match multi-field key by name
4413 if( 0 == strcasecmp(this->name, key_field->name) ) return true;
4414
4415 // A literal key_field is a "magic" literal indicating a key name
4416 // (that didn't match, above).
4417 if( is_literal(key_field) ) return false;
4418
4419 // match single-field key by its symbol index
4420 size_t ifield = field_index(key_field);
4421 if( nfield == 1 && fields[0] == ifield ) return true;
4422
4423 // A literal key_field is a "magic" literal indicating a key name
4424 // (that didn't match, above).
4425 if( is_literal(key_field) ) return false;
4426
4427 // Match if the field has the same offset as the key, and belongs to
4428 // an 01 record for the same FD.
4429 if( this->offset() == key_field->offset ) {
4430 auto this_file( symbol_record_file(cbl_field_of(symbol_at(fields[0]))) );
4431 auto that_file( symbol_record_file(key_field) );
4432 if( this_file && that_file &&
4433 symbol_index(symbol_elem_of(this_file)) ==
4434 symbol_index(symbol_elem_of(that_file)) ) {
4435 this->leftmost = ifield;
4436 return true;
4437 }
4438 }
4439
4440 return false;
4441 }
4442
4443 uint32_t cbl_file_key_t::
4444 key_field_size( uint32_t sum, size_t ifield ) {
4445 return sum + field_size( cbl_field_of(symbol_at(ifield)) );
4446 }
4447
4448 // Return size of named field in key or, if NULL, whole key
4449 uint32_t cbl_file_key_t::
4450 size() {
4451 if( leftmost != 0 ) {
4452 return cbl_field_of(symbol_at(leftmost))->data.capacity;
4453 }
4454 return std::accumulate(fields, fields + nfield, 0, key_field_size);
4455 }
4456
4457
4458 /*
4459 * Produce list of qualifier names for any key field.
4460 */
4461 static std::list<const char *>
4462 symbol_forward_names( size_t ifield ) {
4463 std::list<const char *> output;
4464
4465 for( auto sym = symbols_begin(ifield); sym && sym->type == SymField; ) {
4466 const cbl_field_t *field = cbl_field_of(sym);
4467 if( !(field->type == FldForward) ) {
4468 dbgmsg("%s:%d: logic error, not FldForward: #" HOST_SIZE_T_PRINT_UNSIGNED " %s",
4469 __func__, __LINE__, (fmt_size_t)symbol_index(sym), field_str(field));
4470 }
4471 assert(field->type == FldForward);
4472
4473 output.push_front( field->name );
4474
4475 if( 0 == field->parent) break;
4476 sym = symbols_begin(field->parent);
4477 }
4478
4479 return output;
4480 }
4481
4482 static size_t
4483 symbol_forward_to( size_t fwd ) {
4484 std::list<const char *> names = symbol_forward_names(fwd);
4485 size_t program = symbols_begin(fwd)->program;
4486
4487 std::pair <symbol_elem_t *, bool> elem = symbol_find( program, names );
4488
4489 if( !elem.second ) {
4490 const auto& field = *cbl_field_of(symbols_begin(fwd));
4491 if( yydebug )
4492 dbgmsg("%s:%d: no symbol found for #" HOST_SIZE_T_PRINT_UNSIGNED " %s %s",
4493 __func__, __LINE__,
4494 (fmt_size_t)fwd, cbl_field_type_str(field.type), field.name);
4495 return fwd;
4496 }
4497
4498 return symbol_index(elem.first);
4499 }
4500
4501 /*
4502 * For each FldForward, resolve to a field that is part of an FD
4503 * record for the file.
4504 */
4505 void
4506 cbl_file_key_t::deforward( size_t ifile ) {
4507 const auto file = cbl_file_of(symbol_at(ifile));
4508 std::transform( fields, fields + nfield, fields,
4509 [ifile, file]( size_t fwd ) {
4510 auto ifield = symbol_forward_to(fwd);
4511 const auto field = cbl_field_of(symbol_at(ifield));
4512
4513 if( is_forward(field) && yydebug ) {
4514 static std::map<size_t, int> keys;
4515 dbgmsg("%s:%d: key %d: #" HOST_SIZE_T_PRINT_UNSIGNED " %s of %s is %s",
4516 "deforward", __LINE__,
4517 keys[ifile]++, (fmt_size_t)ifield, field->name, file->name,
4518 cbl_field_type_str(field->type) + 3);
4519 }
4520
4521 auto parent = symbol_record_file(field);
4522
4523 if( ifield == fwd ) {
4524 ERROR_FIELD(field, "line %d: %s of %s "
4525 "is not defined",
4526 field->line, field->name, file->name);
4527 return ifield;
4528 }
4529
4530 // relative files have numeric keys that are not part of the record
4531 if( file->org == file_relative_e ) {
4532 if( parent != NULL ) {
4533 ERROR_FIELD(field, "line %d: RELATIVE file %s key %s "
4534 "is defined in file description",
4535 file->line, file->name, field->name);
4536 return ifield;
4537 }
4538 if( field->occurs.ntimes() ) {
4539 ERROR_FIELD(field, "line %d: RELATIVE file %s key %s "
4540 "cannot have OCCURS clause",
4541 file->line, file->name, field->name);
4542 return ifield;
4543 }
4544 if( ! (is_numeric(field) && 0 == field->data.rdigits) ) {
4545 ERROR_FIELD(field, "line %d: RELATIVE file %s key %s "
4546 "must be integer type",
4547 file->line, file->name, field->name);
4548 return ifield;
4549 }
4550 return ifield;
4551 }
4552 // looked-up field must have same file as parent
4553 if( ! (parent != NULL &&
4554 symbol_index(symbol_elem_of(parent)) == ifile) ) {
4555 const cbl_field_t *undefined =
4556 symbol_unresolved_file_key(file, field->name);
4557 int lineno = undefined? undefined->line : file->line;
4558 ERROR_FIELD(undefined? undefined : field,
4559 "line %d: %s of %s "
4560 "is not defined in file description",
4561 lineno, field->name, file->name);
4562 }
4563 return ifield;
4564 } );
4565 }
4566
4567 char *
4568 cbl_file_key_t::str() const {
4569 char *output = static_cast<char*>( xcalloc(nfield, 8) ), *p = output;
4570 assert(output);
4571 const char *sep = "";
4572
4573 *p++ = '[';
4574 for( auto f = fields; f < fields + nfield; f++) {
4575 auto n = sprintf(p, "%s" HOST_SIZE_T_PRINT_UNSIGNED, sep, (fmt_size_t)*f);
4576 p += n;
4577 sep = ", ";
4578 }
4579 *p++ = ']';
4580 return output;
4581 }
4582
4583 /*
4584 * After processing FILE SECTION, replace forward references with actual ones.
4585 */
4586 void
4587 cbl_file_t::deforward() {
4588 if( user_status ) {
4589 user_status = symbol_forward_to(user_status);
4590
4591 auto field = cbl_field_of(symbol_at(user_status));
4592 if( is_forward(field) ) {
4593 ERROR_FIELD(field, "%s of %s never defined in FD record",
4594 field->name, this->name);
4595 }
4596 }
4597
4598 for( auto p = keys; p < keys + nkey; p++ ) {
4599 p->deforward( symbol_index(symbol_elem_of(this)) );
4600 }
4601 }
4602
4603 char *
4604 cbl_file_t::keys_str() const {
4605 std::string names = "[";
4606 for( cbl_file_key_t *p = keys; p < keys + nkey; p++ ) {
4607 names += p->str();
4608 names += p + 1 < keys + nkey ? "," : "]";
4609 }
4610 return xasprintf("%s", names.c_str());
4611 }
4612
4613 /*
4614 * _FILE_STATUS symbols
4615 */
4616
4617 static struct file_status_field_t {
4618 file_status_t status;
4619 } file_status_fields[] = {
4620 {FsSuccess},
4621 {FsDupRead},
4622 {FsRecordLength},
4623 {FsUnavail},
4624 {FsNotaTape},
4625
4626 {FsEofSeq},
4627 {FsEofRel},
4628
4629 {FsKeySeq},
4630 {FsDupWrite},
4631 {FsNotFound},
4632 {FsEofWrite},
4633
4634 {FsOsError},
4635 {FsBoundary},
4636 {FsNoFile},
4637 {FsNoAccess},
4638 {FsCloseLock},
4639 {FsWrongType},
4640
4641 {FsLogicErr},
4642 {FsIsOpen},
4643 {FsCloseNotOpen},
4644 {FsNoRead},
4645 {FsBoundWrite},
4646 {FsReadError},
4647 {FsReadNotOpen},
4648 {FsNoWrite},
4649 {FsNoDelete},
4650
4651 {FsWrongThread},
4652 {FsPassword},
4653 {FsLogicOther},
4654 {FsNoResource},
4655 {FsIncomplete},
4656 {FsNoDD},
4657 {FsVsamOK},
4658 {FsBadEnvVar},
4659 };
4660
4661 static int
4662 cbl_file_status_cmp( const void *K, const void *E ) {
4663 const struct file_status_field_t
4664 *k=static_cast<const struct file_status_field_t *>(K),
4665 *e=static_cast<const struct file_status_field_t *>(E);
4666 return k->status == e->status? 0 : 1;
4667 }
4668
4669 static long
4670 file_status_status_of( file_status_t status ) {
4671 size_t n = COUNT_OF(file_status_fields);
4672 const file_status_field_t *fs, key { status };
4673
4674 fs = static_cast<file_status_field_t*>(lfind( &key,
4675 file_status_fields,
4676 &n,
4677 sizeof(*fs),
4678 cbl_file_status_cmp ));
4679 return fs? (long)fs->status : -1;
4680 }
4681
4682 cbl_field_t *
4683 ast_file_status_between( file_status_t lower, file_status_t upper ) {
4684 struct { cbl_field_t *lb, *ub, *both; } cond = { new_temporary(FldConditional),
4685 new_temporary(FldConditional),
4686 new_temporary(FldConditional) };
4687
4688 cbl_field_t *file_status = cbl_field_of(symbol_field(0, 0, "_FILE_STATUS"));
4689
4690 long status_lower = file_status_status_of(lower);
4691 long status_upper = file_status_status_of(upper);
4692 assert(status_lower != -1);
4693 assert(status_upper != -1);
4694
4695 parser_relop_long( cond.lb, status_lower, le_op, file_status );
4696 parser_relop_long( cond.ub, status_upper, gt_op, file_status );
4697
4698 parser_logop( cond.both, cond.lb, and_op, cond.ub );
4699
4700 return cond.both;
4701 }
4702
4703 bool
4704 is_register_field(const cbl_field_t *field)
4705 {
4706 // TRUE when the field is an executable-level global variable of the type we
4707 // are calling a "register", like RETURN-CODE or UPSI or the like:
4708 return
4709 ( field->parent == 0
4710 && field->level == 0
4711 && !(field->attr & intermediate_e)
4712 && !(field->attr & filler_e)
4713 && field->type != FldClass
4714 && field->type != FldBlob
4715 );
4716 }
4717
4718 bool
4719 has_value( cbl_field_type_t type ) {
4720 // Indicates that the field type contains data that can be expressed as
4721 // a numeric value
4722 switch ( type ) {
4723 case FldInvalid:
4724 case FldGroup:
4725 case FldAlphanumeric:
4726 case FldNumericEdited:
4727 case FldAlphaEdited:
4728 case FldLiteralA:
4729 case FldClass:
4730 case FldConditional:
4731 case FldForward:
4732 case FldSwitch:
4733 case FldDisplay:
4734 case FldBlob:
4735 return false;
4736 case FldIndex:
4737 case FldPointer:
4738 case FldNumericDisplay:
4739 case FldNumericBinary:
4740 case FldFloat:
4741 case FldPacked:
4742 case FldNumericBin5:
4743 case FldLiteralN:
4744 return true;
4745 }
4746 dbgmsg( "%s:%d: invalid symbol_type_t %d", __func__, __LINE__, type );
4747 return false;
4748 }