From 0b8011604058bf69a44673fe826391255bc33bdf Mon Sep 17 00:00:00 2001
From: "James K. Lowden" <jklowden@symas.com>
Date: Mon, 15 Apr 2024 12:09:52 -0400
Subject: [PATCH] symbol_field_same_as: set parent and level

---
 gcc/cobol/symbols.cc | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/gcc/cobol/symbols.cc b/gcc/cobol/symbols.cc
index ae63ad13300f..8640e6bc65d3 100644
--- a/gcc/cobol/symbols.cc
+++ b/gcc/cobol/symbols.cc
@@ -2357,8 +2357,8 @@ symbol_typedef_add( size_t program, struct cbl_field_t *field ) {
 struct symbol_elem_t *
 symbol_field_add( size_t program, struct cbl_field_t *field )
 {
-  cbl_field_t *parent = symbol_field_parent_set( field );
   field->our_index = symbols.nelem;
+  cbl_field_t *parent = symbol_field_parent_set( field );
   if( parent && parent->type == FldGroup) {
     // Inherit parent's usage, and use it to set the type if not already set.
     // This relies on the parent's FldGroup data matching its USAGE
@@ -2632,6 +2632,19 @@ public:
   const symbol_elem_t *end()   const { return eog; }
 };
 
+static size_t
+seek_parent( const symbol_elem_t *e, size_t level ) {
+  size_t program = e->program;
+  const cbl_field_t *field = cbl_field_of(e);
+  while( program == e->program && level <= field->level ) { 
+    if( e->type != SymField ) break;
+    auto f = cbl_field_of(e);
+    if( f->parent == 0 ) break;
+    e = symbol_at(f->parent);
+  }
+  return symbol_index(e);
+}
+
 /*
  * For SAME AS definition, copy the field metadata and update the parent.
  * For a group, create new fields and copy members recursively.
@@ -2686,6 +2699,7 @@ symbol_field_same_as( cbl_field_t *tgt, const cbl_field_t *src ) {
       that = cbl_field_of(e); // must exist
     }
     memcpy(dup.name, that->name, sizeof(dup.name));
+    dup.occurs = that->occurs;
     dup.level = that->level;
     switch( dup.level ) {
     case 0:
@@ -2696,6 +2710,7 @@ symbol_field_same_as( cbl_field_t *tgt, const cbl_field_t *src ) {
       dup.level += tgt->level;
       break;
     }
+    dup.parent = seek_parent(last_elem, dup.level);
     dup.same_as( *that, src->is_typedef() );
 
     last_elem = symbol_field_add( last_elem->program, &dup );
-- 
GitLab