M2F0

VisualAge Interacoes

Jan 9th, 2026
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Markdown 46.95 KB | None | 0 0

Interações entre Programas VisualAge Generator

Análise Detalhada com Exemplos e Observações

Documento: hptexe45.txt - VisualAge Generator: External Source Format Reference
Data da Análise: 2025-01-08
Objetivo: Identificar e documentar todas as situações em que um programa VisualAge interage com outro programa VisualAge


📑 Índice

  1. Visão Geral das Interações
  2. Mecanismo 1: CALL - Chamada com Retorno
  3. Mecanismo 2: XFER - Transferência Permanente
  4. Mecanismo 3: Chamada de Funções com Parâmetros
  5. Mecanismo 4: Compartilhamento de Working Storage
  6. Exemplos de Sintaxe External Source Format
  7. Matriz de Compatibilidade
  8. Casos de Uso Práticos
  9. Observações Críticas e Restrições
  10. Referências no Documento

1. Visão Geral das Interações

O VisualAge Generator oferece 4 mecanismos principais para interação entre programas:

Mecanismo Retorna Controle? Passa Dados? Ambiente Referência
CALL (CALLED) ✅ Sim ✅ Bidirecional Transacional com UI Linhas 351-365
CALL (CALLBATCH) ✅ Sim ✅ Bidirecional Batch sem UI Linhas 366-367
XFER (MAIN) ❌ Não ✅ Working Storage Transacional Linhas 358-360
XFER (MAINBATCH) ❌ Não ✅ Working Storage Batch Linhas 361-362

Mecanismos Complementares:

  • Chamada de Funções com PARM (Linhas 761-844)
  • Compartilhamento via TABREC (Linhas 398-401)

2. Mecanismo 1: CALL - Chamada com Retorno

2.1 Descrição

Um programa chama outro programa e aguarda seu retorno, permitindo passagem bidirecional de parâmetros.

2.2 Tipos de Programas Chamados

2.2.1 CALLED - Programa Transacional

Referência: Linhas 351-365

Características:

  • Programa interage com usuário (display device)
  • Retorna controle ao programa chamador
  • Usado em ambientes CICS, IMS transacional

Citação do Documento (Linhas 364-365):

"Specify CALLED for a program that is called by and returns to another VisualAge Generator program or non-VisualAge Generator program. The program interacts with a user at a display device. Parameters can be passed between the calling and the called VisualAge Generator programs or non-VisualAge Generator programs."

2.2.2 CALLBATCH - Programa Batch

Referência: Linhas 366-367

Características:

  • Programa NÃO interage com usuário
  • Processamento batch/background
  • Retorna controle ao programa chamador

Citação do Documento (Linhas 366-367):

"Specify CALLBATCH for a program that is called by and returns to another VisualAge Generator program or non-VisualAge Generator program. The program does not interact with a user at a display device. Parameters can be passed between the calling and called VisualAge Generator programs or non-VisualAge Generator programs."

2.3 Tag CALLPARM - Definição de Parâmetros

Referência: Linhas 424-427, 1392-1440

2.3.1 Características Principais

Citação (Linhas 424-425):

"The CALLPARM tag specifies the name and type of each parameter received by a called program. This optional tag with its attributes further describes the PROGRAM and EPROGRAM tag set. The maximum number of parameters is 30."

Regras Críticas (Linha 425):

"Parameters can be maps, records, or data items. List the parameters in the same order as the arguments are listed in the program's CALL statement. The number of parameters must equal the number of arguments."

2.3.2 Tipos de Parâmetros Suportados

Tipo Descrição Referência
MAP Mapas (telas/formulários) Linha 1439
RECORD Registros (working storage) Linha 1437
ITEM Itens de dados individuais Linha 1438

2.3.3 Compatibilidade de Tipos

Citação Crítica (Linha 426):

"The parameter definitions are the same as, or compatible with, the definitions of the call arguments. If data types are not compatible or lengths are not the same, errors might occur during execution."

Restrição Importante (Linha 426):

"A data item parameter cannot be a data item in a record, table, or map used by the called program. You can define the data item using data item definition."

2.3.4 Parâmetros Especiais DL/I

Referência: Linha 1432

Citação:

"Note: EZEDLPSB and EZEDLPCB can be specified as item names but cannot both be specified in the same called parameter list. EZEDLPCB can be subscripted with a numeric literal."

2.4 Exemplo de Sintaxe External Source Format

Referência: Linhas 1477-1490

:program name = PROG001
         type = CALLED
         mapgroup = MAPGRP01
         date = '12/15/2024' 
         time = '10:30:00'.
    :mainfun name = MAIN_FUNCTION.
        MOVE A TO B;
    :emainfun.
    :tabrec name = SHARED_RECORD type = RECORD.
    :callparm name = INPUT_MAP type = MAP.
    :callparm name = DATA_RECORD type = RECORD.
    :callparm name = CONTROL_ITEM type = ITEM.
    :prol.
        This program is called by PROG000 and processes customer data.
        It receives a map, a data record, and a control item.
    :eprol.
:eprogram.

Nota do Documento (Linha 1490):

"Note: This example illustrates the syntax of all program definition tags and attributes. Actual definitions do not require or use all tags and attributes shown here."

2.5 Fluxo de Execução

┌─────────────────────────────────────────────────────────┐
│ Programa A (MAIN ou MAINBATCH)                         │
│                                                         │
│   1. Prepara argumentos (MAP, RECORD, ITEM)           │
│   2. CALL PROG_B (arg1, arg2, arg3)                   │
│   3. [AGUARDA RETORNO]                                 │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa B (CALLED ou CALLBATCH)                       │
│                                                         │
│   :callparm name = arg1 type = MAP.                    │
│   :callparm name = arg2 type = RECORD.                 │
│   :callparm name = arg3 type = ITEM.                   │
│                                                         │
│   4. Recebe parâmetros                                 │
│   5. Processa lógica de negócio                        │
│   6. Modifica parâmetros (se necessário)               │
│   7. RETURN                                            │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa A (continua execução)                         │
│                                                         │
│   8. Recebe controle de volta                          │
│   9. Acessa dados modificados nos argumentos           │
│  10. Continua processamento                            │
│                                                         │
└─────────────────────────────────────────────────────────┘

2.6 Observações Importantes

⚠️ Ordem dos Parâmetros

  • A ordem dos CALLPARM DEVE corresponder exatamente à ordem dos argumentos no CALL
  • Número de parâmetros DEVE ser exato (máximo 30)

⚠️ Map Groups Compartilhados

Citação (Linha 330):

"A called program can use a different map group than the calling program unless a map is a parameter passed to the called program. In this case, the same map group is used."

Implicação: Quando MAP é passado como parâmetro, ambos os programas DEVEM usar o mesmo MAPGROUP.


3. Mecanismo 2: XFER - Transferência Permanente

3.1 Descrição

Um programa transfere controle permanentemente para outro programa. O programa original NÃO recebe controle de volta.

3.2 Tipos de Programas Destino

3.2.1 MAIN - Programa Principal Transacional

Referência: Linhas 358-360

Citação:

"Specify MAIN for a program that interacts with a user at a display device. The program is started through a transfer from the system, a non-VisualAge Generator program, or a VisualAge Generator program. A block of working storage data can be passed to the program upon transfer from another non-VisualAge Generator program or VisualAge Generator program."

Características:

  • Interage com usuário (display device)
  • Iniciado via transfer do sistema ou outro programa
  • Pode receber bloco de working storage na transferência

3.2.2 MAINBATCH - Programa Principal Batch

Referência: Linhas 361-362

Citação:

"Specify MAINBATCH for a program that processes without interacting with a user at a display device. The program is started through a transfer from the system, a non-VisualAge Generator program, or a VisualAge Generator program. A block of working storage data can be passed to the program on transfer from another non-VisualAge Generator program or VisualAge Generator program."

Características:

  • NÃO interage com usuário
  • Processamento batch/background
  • Pode receber bloco de working storage na transferência

3.3 Passagem de Dados via Working Storage

Mecanismo: Bloco de working storage é passado na transferência

Diferença do CALL:

  • CALL: Passa parâmetros específicos (MAP, RECORD, ITEM) via CALLPARM
  • XFER: Passa bloco completo de working storage

3.4 Uso com UI Records

Referência: Linhas 1742-1746

Tag LINKPARM:

"The LINKPARM tags define user interface properties that can be specified for an item in a record, named on a RECDITEM tag, that has a UITYPE of FORM or PROGRAMLINK. This optional tag further defines the UIPROP and EUIPROP tag set."

Citação (Linha 1746):

"The LINKPARM tag cannot be specified without the LINKDATA tag. Repeat the LINKPARM tag for each data item that is to be a parameter when the UI record is passed on an XFER statement. The order of the LINKPARM tags determines the order of the parameters."

3.5 Contexto IMS Single-Segment

Referência: Linha 1225 (EXECMODE=SINGLESEG)

Citação:

"SINGLESEG specifies that the program runs in single-segment mode. It is valid for IMS/VS only. A single-segment program processes a single input from a terminal and ends after it responds to the input or after it transfers to another program. Program information is not saved when the map is displayed."

3.6 Exemplo de Sintaxe External Source Format

:program name = PROG_ORIGEM
         type = MAIN
         mapgroup = MAPGRP01.
    :mainfun name = MAIN_FUNC.
        MOVE DATA TO WORKING_STORAGE_BLOCK;
        XFER PROG_DESTINO PASSING WORKING_STORAGE_BLOCK;
        /* Código abaixo NÃO será executado */
    :emainfun.
:eprogram.

:program name = PROG_DESTINO
         type = MAIN
         mapgroup = MAPGRP01.
    :mainfun name = MAIN_FUNC.
        /* Recebe WORKING_STORAGE_BLOCK */
        /* Assume controle permanentemente */
    :emainfun.
:eprogram.

3.7 Fluxo de Execução

┌─────────────────────────────────────────────────────────┐
│ Programa A (MAIN ou MAINBATCH)                         │
│                                                         │
│   1. Prepara working storage                           │
│   2. XFER PROG_B PASSING WORKING_STORAGE              │
│   3. [PROGRAMA A TERMINA]                              │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 │ (transferência permanente)
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa B (MAIN ou MAINBATCH)                         │
│                                                         │
│   4. Recebe working storage                            │
│   5. Assume controle do sistema                        │
│   6. Processa até conclusão                            │
│   7. [PROGRAMA A NUNCA RECEBE CONTROLE]                │
│                                                         │
└─────────────────────────────────────────────────────────┘

3.8 Observações Importantes

⚠️ Transferência Irreversível

  • Programa origem NÃO recebe controle de volta
  • Código após XFER NÃO é executado

⚠️ Working Storage vs. Parâmetros

  • XFER passa bloco completo de working storage
  • CALL passa parâmetros específicos via CALLPARM

⚠️ Uso em IMS Single-Segment

  • Programa processa uma entrada e termina ou transfere
  • Informações do programa NÃO são salvas após transfer

4. Mecanismo 3: Chamada de Funções com Parâmetros

4.1 Descrição

Programas podem chamar funções (FUNC) definidas no mesmo ou em outros programas, passando parâmetros específicos.

4.2 Tag PARM - Definição de Parâmetros de Função

Referência: Linhas 761-844, 2648-2651

4.2.1 Características Principais

Citação (Linha 761):

"The PARM tag specifies the name and type of each parameter passed to a function. Any number of parameters may be specified."

Diferença do CALLPARM:

  • CALLPARM: Parâmetros de programa (máximo 30)
  • PARM: Parâmetros de função (quantidade ilimitada)

4.3 Tipos de Parâmetros (PARMTYPE)

Referência: Linhas 800-808

4.3.1 RECORD

Citação (Linha 802):

"Specifies that the parameter is a record. The library part must be a working storage record. The corresponding argument must be a record with length at least as long as the parameter record."

4.3.2 ITEM

Citação (Linha 803):

"Specifies that the parameter is an item. The corresponding argument must be an item with a compatible definition or a literal. (default value)"

4.3.3 MAPITEM

Citação (Linhas 804-805):

"Specifies that the parameter is a map item and has map item state information. The corresponding argument must be a map item with a compatible definition."

Observação: MAPITEM inclui informações de estado do map item, permitindo testes e manipulações avançadas.

4.3.4 SQLITEM

Citação (Linhas 806-807):

"Specifies that the parameter is an SQL item and has SQL state information. The corresponding argument must be an SQL item with a compatible definition."

Observação: SQLITEM inclui informações de estado SQL, permitindo verificação de condições SQL.

4.4 Tipagem de Parâmetros

Referência: Linhas 808-844

4.4.1 Loose Typing (ANY Types)

Citação (Linha 835):

"Defining item parameters as one of the ANY item types specifies loose typing of the parameter. Bytes, decimals, and a specific numeric type are not specified for these parameters. Instead, test and generation will determine the appropriate conversion that needs to occur between the argument and the parameter. This may result in multiple copies of the function being produced in the generated code."

Tipos ANY Disponíveis:

  • ANYCHAR (Linha 810)
  • ANYDBCS (Linha 812)
  • ANYHEX (Linha 814)
  • ANYMIXED (Linha 816)
  • ANYNUMERIC (Linha 818)
  • ANYUNICODE (Linha 820)

Vantagem: Flexibilidade - aceita diferentes tamanhos
Desvantagem: Pode gerar múltiplas cópias da função no código gerado

4.4.2 Strong Typing (Tipos Específicos)

Citação (Linha 836):

"Defining item parameters with a data type other than one of the ANY item types specifies strong typing of the parameter. Bytes, decimals, and a specific numeric type are either specified or defaulted for you. Test and generation will require exact matches between arguments and parameters when strong typing is used."

Tipos Específicos:

  • BIN (Binary number)
  • CHA (Character data)
  • DBCS (Double-byte character data)
  • HEX (Hexadecimal data)
  • MIX (Mixed DBCS/single-byte)
  • NUM (Numeric F format)
  • NUMC (Numeric C format)
  • PACK (Packed decimal C format)
  • PACF (Packed decimal F format)
  • UNICODE (Unicode character data)

Vantagem: Validação rigorosa em tempo de compilação
Desvantagem: Requer match exato entre argumento e parâmetro

4.4.3 Restrição para Map Items

Citação (Linhas 837-838):

"For map item parameters, the only valid parameter item types are: NUM, CHA, DBCS, MIX, ANYNUMERIC, ANYCHAR, ANYDBCS, and ANYMIX."

4.5 Exemplo de Sintaxe External Source Format

Referência: Linhas 2643-2675

:func name = VALIDATE_CUSTOMER
      date = '12/15/2024' 
      time = '10:30:00'
      option = EXECUTE 
      desc = 'Validates customer data and returns status code'.
    :parm name = CUSTOMER_RECORD 
          parmtype = RECORD 
          desc = 'Customer record to validate'.
    :parm name = VALIDATION_FLAG 
          parmtype = ITEM 
          type = NUM 
          bytes = 3 
          decimals = 0 
          desc = 'Validation result flag' 
          usage = NONSHARED.
    :parm name = CUSTOMER_NAME_FIELD 
          parmtype = MAPITEM 
          type = CHA 
          bytes = 50 
          desc = 'Customer name from map'.
    :storage name = LOCAL_COUNTER 
             stortype = ITEM 
             type = NUM 
             bytes = 5 
             decimals = 0 
             desc = 'Local counter for validation'.
    :return bytes = 3 
            decimals = 0 
            type = NUM 
            desc = 'Return code: 0=OK, 1=Error, 2=Warning'.
    :before.
        SET LOCAL_COUNTER TO 0;
        VALIDATE CUSTOMER_RECORD;
    :ebefore.
    :after.
        IF VALIDATION_FLAG = 1 THEN
            SET RETURN_VALUE TO 1;
        ELSE
            SET RETURN_VALUE TO 0;
        END-IF;
    :eafter.
:efunc.

Nota do Documento (Linha 2675):

"Note: This example illustrates the syntax of all function definition tags and attributes. Actual definitions do not require or use all tags and attributes shown here."

4.6 Fluxo de Execução

┌─────────────────────────────────────────────────────────┐
│ Programa A                                              │
│                                                         │
│   1. Prepara argumentos                                │
│   2. CALL FUNCTION_X (RECORD, MAPITEM, ITEM)          │
│   3. [AGUARDA RETORNO]                                 │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Função X (pode estar em Programa A ou B)               │
│                                                         │
│   :parm name = param1 parmtype = RECORD.               │
│   :parm name = param2 parmtype = MAPITEM.              │
│   :parm name = param3 parmtype = ITEM.                 │
│                                                         │
│   4. Recebe parâmetros                                 │
│   5. Executa lógica (BEFORE/AFTER)                     │
│   6. Acessa estado de MAPITEM/SQLITEM                  │
│   7. Retorna valor (RETURN)                            │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa A (continua execução)                         │
│                                                         │
│   8. Recebe valor de retorno                           │
│   9. Acessa parâmetros modificados                     │
│  10. Continua processamento                            │
│                                                         │
└─────────────────────────────────────────────────────────┘

4.7 Observações Importantes

⚠️ MAPITEM e SQLITEM - Estado Avançado

  • Permitem acesso a informações de estado (modified, null, etc.)
  • Apenas tipos específicos são válidos (NUM, CHA, DBCS, MIX, ANY*)

⚠️ Loose vs. Strong Typing

  • *Loose (ANY):** Flexível, mas pode gerar múltiplas cópias da função
  • Strong (tipos específicos): Rígido, mas mais eficiente

⚠️ Quantidade Ilimitada

  • Diferente de CALLPARM (máximo 30), PARM não tem limite especificado

5. Mecanismo 4: Compartilhamento de Working Storage

5.1 Descrição

Programas compartilham dados através de records adicionais definidos em working storage via tag TABREC.

5.2 Tag TABREC - Definição

Referência: Linhas 398-401

Citação (Linhas 398-400):

"The TABREC tag, which can be repeated, specifies the following:

  • Each table used in the program, including edit tables for data items on a map. The list of tables is used to verify references to tables by processing statements and to assure the tables are available when the program runs. This list will not include message tables picked up because of the message table prefix specified with the program.
  • Each record used as an additional working storage area, an argument passed on a call, or a record redefinition referred to in the program that is not the object of one of the functions in the program."

5.3 Usos da TABREC

5.3.1 Working Storage Adicional

  • Define áreas de memória adicionais para o programa

5.3.2 Argumentos Passados em CALL

Citação (Linha 400):

"Each record used as an additional working storage area, an argument passed on a call, or a record redefinition referred to in the program that is not the object of one of the functions in the program."

5.3.3 Redefinições de Record

  • Permite estruturas alternativas de dados sobre o mesmo espaço de memória

5.4 Exemplo de Sintaxe External Source Format

Referência: Linha 1484 (exemplo de programa)

:program name = PROG_CALLER
         type = MAIN
         mapgroup = MAPGRP01.
    :mainfun name = MAIN_FUNC.
        MOVE DATA TO SHARED_RECORD;
        CALL PROG_CALLED (SHARED_RECORD);
        /* SHARED_RECORD pode ter sido modificado */
        PROCESS SHARED_RECORD;
    :emainfun.
    :tabrec name = SHARED_RECORD type = RECORD.
    :tabrec name = EDIT_TABLE type = TABLE.
:eprogram.

:program name = PROG_CALLED
         type = CALLED
         mapgroup = MAPGRP01.
    :mainfun name = MAIN_FUNC.
        /* Recebe e processa SHARED_RECORD */
        MODIFY SHARED_RECORD;
    :emainfun.
    :callparm name = SHARED_RECORD type = RECORD.
:eprogram.

5.5 Fluxo de Compartilhamento

┌─────────────────────────────────────────────────────────┐
│ Programa A                                              │
│                                                         │
│   :tabrec name = SHARED_RECORD type = RECORD.          │
│                                                         │
│   1. Define SHARED_RECORD em working storage           │
│   2. Popula SHARED_RECORD com dados                    │
│   3. CALL PROG_B (SHARED_RECORD)                       │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa B                                              │
│                                                         │
│   :callparm name = SHARED_RECORD type = RECORD.        │
│                                                         │
│   4. Recebe referência a SHARED_RECORD                 │
│   5. Lê/modifica SHARED_RECORD                         │
│   6. RETURN                                            │
│                                                         │
└────────────────┬────────────────────────────────────────┘
                 │
                 ▼
┌─────────────────────────────────────────────────────────┐
│ Programa A (continua)                                   │
│                                                         │
│   7. Acessa SHARED_RECORD modificado                   │
│   8. Continua processamento                            │
│                                                         │
└─────────────────────────────────────────────────────────┘

5.6 Map Groups e TABREC

Referência: Linha 330

Citação:

"A called program can use a different map group than the calling program unless a map is a parameter passed to the called program. In this case, the same map group is used."

Implicação:

  • Se MAP é passado via CALLPARM, mesmo MAPGROUP deve ser usado
  • Se apenas RECORD é passado, MAPGROUP pode ser diferente

5.7 Observações Importantes

⚠️ Tabelas de Edição

  • TABREC também lista tabelas de edição usadas em maps
  • Garante disponibilidade em runtime

⚠️ Records Redefinidos

  • Permite múltiplas "visões" do mesmo espaço de memória
  • Útil para conversões de formato

⚠️ Compartilhamento Implícito

  • TABREC documenta o compartilhamento
  • Passagem real ocorre via CALLPARM

6. Exemplos de Sintaxe External Source Format

6.1 Programa CALLED Completo

Referência: Linhas 1477-1490

:program name = CUSTVAL
         date = '12/15/2024' 
         time = '10:30:00'
         type = CALLED
         execmode = NONSEGMENTED
         workstor = WORK_STORAGE_REC
         mapgroup = CUSTMAPS
         helpgrp = HELPMAPS
         helpkey = 1
         psb = CUSTPSB
         pfequate = Y
         implicit = Y
         msgtable = MSGS
         bypkey = 3 12 24
         firstmap = CUSTMAP1.
    :mainfun name = VALIDATE_CUSTOMER.
        /* Lógica de validação */
        MOVE CUST-NAME TO VALIDATED-NAME;
        IF CUST-STATUS = 'A' THEN
            SET VALID-FLAG TO 1;
        ELSE
            SET VALID-FLAG TO 0;
        END-IF;
    :emainfun.
    :tabrec name = CUSTOMER_RECORD type = RECORD.
    :tabrec name = VALIDATION_TABLE type = TABLE.
    :callparm name = CUST_INPUT_MAP type = MAP.
    :callparm name = CUSTOMER_RECORD type = RECORD.
    :callparm name = VALID_FLAG type = ITEM.
    :prol.
        This program validates customer information.
        Called by CUSTMAIN program.
        Receives customer map, record, and validation flag.
        Returns validation status.
    :eprol.
:eprogram.

6.2 Função com Múltiplos Parâmetros

Referência: Linhas 2643-2675

:func name = CALCULATE_DISCOUNT
      date = '12/15/2024'
      time = '14:45:00'
      option = EXECUTE
      desc = 'Calculates customer discount based on purchase history'.
    :parm name = CUSTOMER_ID
          parmtype = ITEM
          type = NUM
          bytes = 10
          decimals = 0
          desc = 'Customer identification number'
          usage = NONSHARED.
    :parm name = PURCHASE_AMOUNT
          parmtype = ITEM
          type = PACK
          bytes = 7
          decimals = 2
          desc = 'Total purchase amount'
          usage = NONSHARED.
    :parm name = DISCOUNT_RATE
          parmtype = ITEM
          type = PACK
          bytes = 3
          decimals = 2
          desc = 'Calculated discount rate (output)'
          usage = NONSHARED.
    :parm name = CUSTOMER_RECORD
          parmtype = RECORD
          desc = 'Customer master record'.
    :storage name = TEMP_AMOUNT
             stortype = ITEM
             type = PACK
             bytes = 7
             decimals = 2
             desc = 'Temporary calculation storage'
             usage = NONSHARED.
    :return bytes = 1
            decimals = 0
            type = NUM
            desc = 'Return code: 0=Success, 1=Error'.
    :before.
        SET TEMP_AMOUNT TO 0;
        READ CUSTOMER_RECORD BY CUSTOMER_ID;
    :ebefore.
    :after.
        IF PURCHASE_AMOUNT > 1000 THEN
            SET DISCOUNT_RATE TO 0.15;
        ELSE IF PURCHASE_AMOUNT > 500 THEN
            SET DISCOUNT_RATE TO 0.10;
        ELSE
            SET DISCOUNT_RATE TO 0.05;
        END-IF;
        SET RETURN_VALUE TO 0;
    :eafter.
:efunc.

6.3 Programa MAINBATCH com XFER

:program name = BATCHJOB01
         type = MAINBATCH
         date = '12/15/2024'
         time = '08:00:00'
         workstor = BATCH_WORK_STORAGE.
    :mainfun name = PROCESS_BATCH.
        /* Processa lote inicial */
        OPEN FILE CUSTOMER_FILE;
        READ CUSTOMER_FILE INTO CUSTOMER_RECORD;

        /* Prepara working storage para próximo job */
        MOVE BATCH_CONTROL_DATA TO WORK_STORAGE;

        /* Transfere para próximo job */
        XFER BATCHJOB02 PASSING WORK_STORAGE;

        /* Código abaixo NÃO será executado */
        CLOSE FILE CUSTOMER_FILE;
    :emainfun.
    :tabrec name = CUSTOMER_RECORD type = RECORD.
    :tabrec name = BATCH_CONTROL_DATA type = RECORD.
:eprogram.

:program name = BATCHJOB02
         type = MAINBATCH
         date = '12/15/2024'
         time = '08:00:00'
         workstor = BATCH_WORK_STORAGE.
    :mainfun name = CONTINUE_BATCH.
        /* Recebe working storage de BATCHJOB01 */
        /* Continua processamento */
        PROCESS WORK_STORAGE;
    :emainfun.
:eprogram.

6.4 Programa com MAPITEM Parameter

:func name = VALIDATE_MAP_FIELD
      option = EXECUTE
      desc = 'Validates a map field and sets error indicators'.
    :parm name = FIELD_TO_VALIDATE
          parmtype = MAPITEM
          type = CHA
          bytes = 50
          desc = 'Map field to validate'
          usage = NONSHARED.
    :parm name = ERROR_MESSAGE
          parmtype = ITEM
          type = CHA
          bytes = 80
          desc = 'Error message if validation fails'
          usage = NONSHARED.
    :return bytes = 1
            type = NUM
            desc = '1 if valid, 0 if invalid'.
    :before.
        /* Verifica se campo foi modificado */
        IF FIELD_TO_VALIDATE IS MODIFIED THEN
            /* Valida conteúdo */
            IF FIELD_TO_VALIDATE IS EMPTY THEN
                SET ERROR_MESSAGE TO 'Field cannot be empty';
                SET RETURN_VALUE TO 0;
            ELSE
                SET RETURN_VALUE TO 1;
            END-IF;
        ELSE
            /* Campo não foi modificado, considera válido */
            SET RETURN_VALUE TO 1;
        END-IF;
    :ebefore.
:efunc.

7. Matriz de Compatibilidade

7.1 Tipos de Programas e Interações

Programa Origem Pode CALL Pode XFER Recebe CALL Recebe XFER
MAIN ✅ CALLED, CALLBATCH ✅ MAIN, MAINBATCH ❌ Não ✅ Sim
MAINBATCH ✅ CALLBATCH ✅ MAIN, MAINBATCH ❌ Não ✅ Sim
CALLED ✅ CALLED, CALLBATCH ✅ MAIN, MAINBATCH ✅ Sim ❌ Não
CALLBATCH ✅ CALLBATCH ✅ MAINBATCH ✅ Sim ❌ Não
WEBMAIN ✅ CALLED, CALLBATCH ✅ MAIN, MAINBATCH ❌ Não ✅ Sim

7.2 Tipos de Parâmetros por Mecanismo

Mecanismo MAP RECORD ITEM MAPITEM SQLITEM Working Storage
CALL (CALLPARM)
XFER
Function (PARM)
TABREC

7.3 Compatibilidade de Tipos de Dados (PARM)

Tipo Parâmetro BIN CHA DBCS HEX MIX NUM NUMC PACK PACF UNICODE
ITEM
MAPITEM
SQLITEM
ANYCHAR
ANYDBCS
ANYHEX
ANYMIXED
ANYNUMERIC
ANYUNICODE

Referência: Linhas 810-820, 837-838


8. Casos de Uso Práticos

8.1 Caso 1: Validação de Cliente (CALL CALLED)

Cenário: Programa principal de cadastro chama subprograma de validação que interage com o usuário.

CUSTMAIN (MAIN)
    ↓ CALL
CUSTVAL (CALLED) - valida com usuário
    ↓ RETURN
CUSTMAIN - continua cadastro

Características:

  • CUSTVAL interage com usuário para confirmar dados
  • Retorna status de validação
  • CUSTMAIN aguarda resposta

8.2 Caso 2: Processamento Batch em Cadeia (CALL CALLBATCH)

Cenário: Job batch principal chama múltiplos subjobs para processamento paralelo.

BATCHMAIN (MAINBATCH)
    ↓ CALL
BATCHSUB1 (CALLBATCH) - processa lote 1
    ↓ RETURN
BATCHMAIN
    ↓ CALL
BATCHSUB2 (CALLBATCH) - processa lote 2
    ↓ RETURN
BATCHMAIN - consolida resultados

Características:

  • Nenhum programa interage com usuário
  • Processamento sequencial de lotes
  • Retorno de status para consolidação

8.3 Caso 3: Menu de Navegação (XFER MAIN)

Cenário: Sistema de menu transfere controle para diferentes módulos.

MAINMENU (MAIN)
    [Usuário seleciona opção]
    ↓ XFER
CUSTMODULE (MAIN) - módulo de clientes
    [Processa até conclusão]
    ↓ XFER
MAINMENU - volta ao menu

Características:

  • Transferência permanente entre módulos
  • Cada módulo é independente
  • Working storage passado entre transferências

8.4 Caso 4: Cadeia de Jobs Batch (XFER MAINBATCH)

Cenário: Jobs batch encadeados processam diferentes etapas.

EXTRACT (MAINBATCH)
    [Extrai dados]
    ↓ XFER (working storage)
TRANSFORM (MAINBATCH)
    [Transforma dados]
    ↓ XFER (working storage)
LOAD (MAINBATCH)
    [Carrega dados]

Características:

  • Pipeline ETL (Extract-Transform-Load)
  • Cada job termina após XFER
  • Working storage carrega dados de controle

8.5 Caso 5: Função de Validação Reutilizável (PARM)

Cenário: Múltiplos programas usam mesma função de validação.

PROG_A → CALL VALIDATE_FUNC (RECORD, MAPITEM)
PROG_B → CALL VALIDATE_FUNC (RECORD, MAPITEM)
PROG_C → CALL VALIDATE_FUNC (RECORD, MAPITEM)

Características:

  • Função centralizada
  • Reutilização de código
  • MAPITEM permite acesso a estado do campo

8.6 Caso 6: Compartilhamento de Dados (TABREC)

Cenário: Programa principal e subprogramas compartilham estrutura de dados comum.

MAIN_PROG (MAIN)
    :tabrec name = SHARED_DATA type = RECORD.
    ↓ CALL
SUB_PROG1 (CALLED)
    :callparm name = SHARED_DATA type = RECORD.
    [Modifica SHARED_DATA]
    ↓ RETURN
MAIN_PROG
    [Acessa SHARED_DATA modificado]
    ↓ CALL
SUB_PROG2 (CALLED)
    :callparm name = SHARED_DATA type = RECORD.
    [Usa SHARED_DATA]

Características:

  • Dados compartilhados entre múltiplos programas
  • Modificações visíveis para todos
  • TABREC documenta o compartilhamento

9. Observações Críticas e Restrições

9.1 Ordem e Quantidade de Parâmetros

⚠️ CALLPARM - Ordem Exata Obrigatória

Referência: Linha 425

Citação:

"List the parameters in the same order as the arguments are listed in the program's CALL statement. The number of parameters must equal the number of arguments."

Implicação:

/* Programa Chamador */
CALL SUBPROG (MAP1, REC1, ITEM1);

/* Programa Chamado - DEVE ter mesma ordem */
:callparm name = MAP1 type = MAP.
:callparm name = REC1 type = RECORD.
:callparm name = ITEM1 type = ITEM.

⚠️ Máximo de 30 Parâmetros (CALLPARM)

Referência: Linha 425

Citação:

"The maximum number of parameters is 30."

Implicação: Se precisar passar mais de 30 valores, use RECORD para agrupar dados.

9.2 Compatibilidade de Tipos

⚠️ Erros em Runtime por Incompatibilidade

Referência: Linha 426

Citação:

"If data types are not compatible or lengths are not the same, errors might occur during execution."

Implicação: Validação é em runtime, não em compile-time. Teste cuidadosamente.

⚠️ Restrição de Data Items em CALLPARM

Referência: Linha 426

Citação:

"A data item parameter cannot be a data item in a record, table, or map used by the called program."

Implicação: Não pode passar RECORD.FIELD como ITEM se RECORD já é usado pelo programa chamado.

9.3 Map Groups

⚠️ Map Group Obrigatório Compartilhado

Referência: Linha 330

Citação:

"A called program can use a different map group than the calling program unless a map is a parameter passed to the called program. In this case, the same map group is used."

Implicação:

/* Programa A */
:program name = PROG_A mapgroup = MAPGRP01.
    CALL PROG_B (MAP_FROM_MAPGRP01);
:eprogram.

/* Programa B - DEVE usar MAPGRP01 */
:program name = PROG_B mapgroup = MAPGRP01.
    :callparm name = MAP_FROM_MAPGRP01 type = MAP.
:eprogram.

9.4 MAPITEM e SQLITEM - Tipos Restritos

⚠️ Tipos Válidos para MAPITEM

Referência: Linhas 837-838

Citação:

"For map item parameters, the only valid parameter item types are: NUM, CHA, DBCS, MIX, ANYNUMERIC, ANYCHAR, ANYDBCS, and ANYMIX."

Tipos PROIBIDOS para MAPITEM:

  • BIN
  • HEX
  • NUMC
  • PACK
  • PACF
  • UNICODE

9.5 Error Handling

⚠️ Rotinas de Erro e Transferência de Controle

Referência: Linhas 686-688

Citação (Linha 687):

"If the error routine is a main function, control is transferred to that function if an error occurs. Otherwise, control returns to the statement following the I/O option after the error routine returns."

Citação (Linha 688):

"Error routines cannot be specified for functions with map I/O objects or for EXECUTE functions. DISPLAY or CONVERSE errors cause the program to end."

Implicações:

  • Erro em DISPLAY/CONVERSE → Programa termina
  • Erro em função com ERRRTN → Transfere controle
  • EXECUTE functions não podem ter ERRRTN

9.6 DL/I Parâmetros Especiais

⚠️ EZEDLPSB e EZEDLPCB

Referência: Linha 1432

Citação:

"Note: EZEDLPSB and EZEDLPCB can be specified as item names but cannot both be specified in the same called parameter list. EZEDLPCB can be subscripted with a numeric literal."

Implicação: Escolha UM dos dois para acesso DL/I:

  • EZEDLPSB: Acesso via PSB
  • EZEDLPCB: Acesso via PCB (pode ser subscrito: EZEDLPCB(1), EZEDLPCB(2))

9.7 XFER - Código Não Executado

⚠️ Código Após XFER é Ignorado

Contexto: Linha 1225

Implicação:

XFER NEXT_PROGRAM PASSING WORK_STORAGE;
/* TODO CÓDIGO ABAIXO NÃO SERÁ EXECUTADO */
CLOSE FILE CUSTOMER_FILE;  /* NUNCA executado */
DISPLAY MESSAGE;            /* NUNCA executado */

9.8 Loose Typing - Múltiplas Cópias

⚠️ ANY Types Geram Código Duplicado

Referência: Linha 835

Citação:

"This may result in multiple copies of the function being produced in the generated code."

Implicação: Usar ANYCHAR, ANYNUMERIC, etc. pode aumentar tamanho do executável gerado.

9.9 Import e Validação

⚠️ Validação Limitada no Import

Referência: Linhas 4000-4001

Citação:

"Import does not compare definitions to be imported with parts that exist in the library. This can cause errors. For example, if the part you import is already in the library as an EXECUTE or file input/output function, and you replace the imported part with a CONVERSE function, then any batch program in the library that uses the function is now in error."

Implicação: Import valida sintaxe, mas não valida compatibilidade entre partes. Teste após import.


10. Referências no Documento

10.1 Seções Principais

Tópico Linhas Descrição
PROGRAM Tag 243-246 Definição de programa e tags relacionadas
TYPE Attribute 282-369 Tipos de programa (MAIN, MAINBATCH, CALLED, CALLBATCH, WEBMAIN)
CALLPARM Tag 424-456, 1392-1440 Definição de parâmetros de programa
TABREC Tag 398-422 Tabelas e records adicionais
PROL Tag 458-472, 1443-1472 Prólogo do programa
Program Example 1477-1490 Exemplo completo de programa
FUNC Tag 616-619 Definição de função
PARM Tag 761-844 Parâmetros de função
PARMTYPE Values 800-844 Tipos de parâmetros (RECORD, ITEM, MAPITEM, SQLITEM)
Function Example 2643-2675 Exemplo completo de função
LINKPARM Tag 1744-1746 Parâmetros para XFER com UI records
EXECMODE 295-309, 1217-1225 Modos de execução (NONSEGMENTED, SEGMENTED, SINGLESEG)
MAPGROUP 327-331, 1248-1251 Map groups e compartilhamento
Error Routines 684-688 Rotinas de tratamento de erro
Import Validation 3998-4001 Limitações de validação no import

10.2 Citações-Chave por Mecanismo

CALL (CALLED)

  • Definição: Linhas 364-365
  • Parâmetros: Linhas 424-427
  • Ordem: Linha 425
  • Compatibilidade: Linha 426

CALL (CALLBATCH)

  • Definição: Linhas 366-367
  • Uso: Mesmas regras de CALLED, sem UI

XFER (MAIN)

  • Definição: Linhas 358-360
  • Working Storage: Linha 360
  • LINKPARM: Linhas 1742-1746

XFER (MAINBATCH)

  • Definição: Linhas 361-362
  • Working Storage: Linha 362
  • SINGLESEG: Linha 1225

Function PARM

  • Definição: Linha 761
  • PARMTYPE: Linhas 800-808
  • Loose Typing: Linha 835
  • Strong Typing: Linha 836
  • MAPITEM Restriction: Linhas 837-838

TABREC

  • Definição: Linhas 398-401
  • Uso em CALL: Linha 400
  • Map Group Sharing: Linha 330

11. Conclusão

O VisualAge Generator oferece um sistema robusto e flexível para interação entre programas, com 4 mecanismos principais:

✅ Pontos Fortes

  1. Flexibilidade: Múltiplos mecanismos para diferentes necessidades
  2. Tipagem: Suporta loose e strong typing
  3. Estado: MAPITEM e SQLITEM permitem acesso a informações de estado
  4. Compartilhamento: TABREC facilita compartilhamento de dados
  5. Interoperabilidade: Funciona com programas não-VisualAge

⚠️ Pontos de Atenção

  1. Validação Runtime: Incompatibilidades só aparecem em execução
  2. Ordem Crítica: Ordem de parâmetros deve ser exata
  3. Limite de Parâmetros: Máximo 30 em CALLPARM
  4. Map Group Sharing: Obrigatório quando MAP é parâmetro
  5. Import Limitado: Não valida compatibilidade entre partes

🎯 Recomendações

  1. Documentar: Use PROL para documentar interfaces
  2. Testar: Validação é em runtime, teste extensivamente
  3. Agrupar: Use RECORD para passar múltiplos valores
  4. Padronizar: Defina convenções de nomenclatura
  5. Reutilizar: Use funções (FUNC) para lógica comum

Documento gerado a partir de: hptexe45.txt - VisualAge Generator: External Source Format Reference
Data: 2025-01-08
Versão: 1.0

Add Comment
Please, Sign In to add comment