diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/DEPENDENCY_REFERENCE.md b/AS400/COBOL_examples/CallingExample/QCBLLESRC/DEPENDENCY_REFERENCE.md new file mode 100644 index 0000000..01b2f45 --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/DEPENDENCY_REFERENCE.md @@ -0,0 +1,561 @@ +# COBOL Dependency Reference - CallingExample + +## Overview +This document provides a comprehensive analysis of the COBOL program dependencies within the CallingExample project. The project demonstrates various COBOL calling patterns on AS400/IBM i systems. + +> ๐Ÿ”ง **NEW: Automation Tools Available!** Check out the [`tools/`](tools/) directory for automated dependency scanning, code validation, templates, and build instructions to streamline your COBOL development workflow. + +## Program Inventory + +| Program | Type | Purpose | Lines of Code | +|---------|------|---------|---------------| +| CALLER.CBLLE | Main Program | External program calling example | 17 | +| CALLER2.CBLLE | Main Program | Duplicate of CALLER.CBLLE | 17 | +| HERON.CBLLE | Called Program | Triangle area calculation using Heron's formula | 24 | +| NESTEDCALL.CBLLE | Main Program | Nested program calling example | 43 | + +## Dependency Structure + +### Program Call Dependencies + +```mermaid +graph TB + A[CALLER.CBLLE] -->|CALL PROGRAM| B[HERON.CBLLE] + C[CALLER2.CBLLE] -->|CALL PROGRAM| D[HERON.CBLLE] + E[NESTEDCALL.CBLLE] -->|Nested CALL| F[HERON
Nested Program] + + style A fill:#e1f5fe + style C fill:#e1f5fe + style E fill:#e1f5fe + style B fill:#f3e5f5 + style D fill:#f3e5f5 + style F fill:#fff3e0 +``` + +#### External Program Calls +- **CALLER.CBLLE** โ†’ **HERON.CBLLE** + - Call Type: External program call + - Parameters: A, B, C (triangle sides), AREA (result) + - Call Statement: `CALL PROGRAM "HERON" USING A B C AREA` + +- **CALLER2.CBLLE** โ†’ **HERON.CBLLE** + - Call Type: External program call + - Parameters: A, B, C (triangle sides), AREA (result) + - Call Statement: `CALL PROGRAM "HERON" USING A B C AREA` + +#### Nested Program Calls +- **NESTEDCALL.CBLLE** contains nested **HERON** program + - Call Type: Nested program call + - Parameters: A, B, C (triangle sides), AREA (result) + - Call Statement: `CALL "HERON" USING A B C AREA` + +### Data Flow Dependencies + +#### Common Data Structures +All programs share a consistent data structure pattern: + +```cobol +01 A PACKED-DECIMAL PICTURE S9(10)V9(5) +01 B PACKED-DECIMAL PICTURE S9(10)V9(5) +01 C PACKED-DECIMAL PICTURE S9(10)V9(5) +01 AREA PACKED-DECIMAL PICTURE S9(10)V9(5) +``` + +#### Parameter Flow + +| Parameter | Direction | Purpose | Data Type | +|-----------|-----------|---------|-----------| +| A | IN | Triangle side length | PACKED-DECIMAL S9(10)V9(5) | +| B | IN | Triangle side length | PACKED-DECIMAL S9(10)V9(5) | +| C | IN | Triangle side length | PACKED-DECIMAL S9(10)V9(5) | +| AREA | OUT | Calculated triangle area | PACKED-DECIMAL S9(10)V9(5) | + +#### Data Transformation +``` +Input: Triangle sides (A, B, C) + โ†“ +HERON Program Logic: + 1. Validate triangle sides (triangle inequality) + 2. Calculate semi-perimeter: S = (A + B + C) / 2 + 3. Apply Heron's formula: AREA = โˆš(S ร— (S-A) ร— (S-B) ร— (S-C)) + โ†“ +Output: Triangle area (AREA) or -1.0 for invalid triangles +``` + +### Copybook Dependencies +**No copybooks found** - All data structures are defined locally within each program. + +### Circular Dependencies Analysis +**No circular dependencies detected** - The call structure is unidirectional: +- Main programs call HERON +- HERON does not call back to main programs +- No mutual dependencies between programs + +## Legacy Patterns Analysis + +### AS400/IBM i Specific Patterns + +1. **PACKED-DECIMAL Usage** + - All numeric variables use PACKED-DECIMAL data type + - Standard AS400 pattern for efficient storage and performance + - Picture clause: `S9(10)V9(5)` (10 integer digits, 5 decimal places, signed) + +2. **Program Calling Conventions** + - External calls use `CALL PROGRAM` syntax + - Nested calls use `CALL` without PROGRAM keyword + - Parameter passing via USING clause + +3. **LINKAGE SECTION Pattern** + - HERON.CBLLE properly defines LINKAGE SECTION for external calls + - Parameters redefined in LINKAGE SECTION match calling program structure + +4. **GOBACK vs STOP RUN** + - Called programs use GOBACK (proper pattern for called programs) + - Main programs should use STOP RUN (not consistently implemented) + +### Code Quality Issues + +#### Variable Name Inconsistencies +- **CALLER.CBLLE & CALLER2.CBLLE**: Reference undefined variable `PLOCHA-DISPLAYED` + - Should reference `AREA-DISP` (defined on line 9) + - Line 15: `DISPLAY "AREA = " PLOCHA-DISPLAYED` should be `DISPLAY "AREA = " AREA-DISP` + +- **NESTEDCALL.CBLLE**: Reference undefined variables `PLOCHA` and `PLOCHA-DISPLAYED` + - Should reference `AREA` and `AREA-DISP` respectively + - Line 13: `MOVE PLOCHA TO PLOCHA-DISPLAYED` should be `MOVE AREA TO AREA-DISP` + - Line 14: `DISPLAY "PLOCHA = " PLOCHA-DISPLAYED` should be `DISPLAY "AREA = " AREA-DISP` + +## Modularity Recommendations + +### Current Strengths +1. **Clear Separation of Concerns**: HERON program focused solely on mathematical calculation +2. **Reusable Design**: HERON can be called from multiple programs +3. **Consistent Interface**: All programs use same parameter structure + +### Improvement Recommendations + +#### 1. Code Deduplication +- **Issue**: CALLER.CBLLE and CALLER2.CBLLE are identical +- **Recommendation**: Remove duplicate program or differentiate functionality + +#### 2. Error Handling Enhancement +```cobol +* Current pattern in HERON: +IF A >= B + C OR B >= A + C OR C >= A + B + MOVE -1.0 TO AREA + GOBACK +END-IF + +* Recommended enhancement: +01 ERROR-CODE PIC 9(2) VALUE 0. + 88 VALID-TRIANGLE VALUE 0. + 88 INVALID-TRIANGLE VALUE 1. + +IF A >= B + C OR B >= A + C OR C >= A + B + SET INVALID-TRIANGLE TO TRUE + MOVE -1.0 TO AREA +ELSE + SET VALID-TRIANGLE TO TRUE + * Continue with calculation +END-IF +``` + +#### 3. Copybook Introduction +Create shared copybooks for: +- Common data structures (`TRIANGLE-PARAMETERS.CPY`) +- Error codes and messages (`ERROR-CODES.CPY`) +- Display formats (`DISPLAY-FORMATS.CPY`) + +#### 4. Standardized Naming Convention +- Implement consistent variable naming across all programs +- Use meaningful names (e.g., `TRIANGLE-AREA` instead of `AREA`) +- Follow AS400 naming conventions consistently + +#### 5. Program Structure Enhancement +```cobol +* Recommended main program structure: +PROCEDURE DIVISION. +0000-MAIN-PROCESS. + PERFORM 1000-INITIALIZE + PERFORM 2000-PROCESS-CALCULATION + PERFORM 3000-DISPLAY-RESULTS + PERFORM 9000-TERMINATE + STOP RUN. + +1000-INITIALIZE. + * Initialization logic + +2000-PROCESS-CALCULATION. + CALL PROGRAM "HERON" USING A B C AREA + +3000-DISPLAY-RESULTS. + * Display logic + +9000-TERMINATE. + * Cleanup logic +``` + +## Quick Start with Automation Tools + +To leverage the new automation capabilities: + +### 1. ๐Ÿ” Validate Code Quality +```bash +cd /path/to/QCBLLESRC +./tools/validate-variables.sh *.CBLLE +``` + +### 2. ๐Ÿ“Š Generate Dependency Report +```powershell +cd /path/to/QCBLLESRC +.\tools\dependency-scanner.ps1 -SourcePath "." -OutputFormat "markdown" -OutputFile "current-analysis.md" +``` + +### 3. ๐Ÿš€ Create New Programs +```bash +cp tools/PROGRAM-TEMPLATE.CBLLE NEW-PROGRAM.CBLLE +# Edit and customize the template +``` + +### 4. ๐Ÿ—๏ธ Build and Deploy +```bash +# Follow detailed instructions in tools/BUILD_INSTRUCTIONS.md +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) +``` + +> ๐Ÿ“ **Complete documentation:** [`tools/README.md`](tools/README.md) + +## Dependencies Summary + +- **Total Programs**: 4 +- **External Dependencies**: 2 (CALLER โ†’ HERON, CALLER2 โ†’ HERON) +- **Nested Dependencies**: 1 (NESTEDCALL contains HERON) +- **Copybook Dependencies**: 0 +- **Circular Dependencies**: 0 +- **Data Dependencies**: Shared parameter structure across all programs + +## Migration Considerations + +When modernizing this codebase: + +1. **Maintain AS400 Data Types**: PACKED-DECIMAL is optimal for AS400 performance +2. **Preserve Call Structure**: The modular design is sound +3. **Address Variable Name Issues**: Fix undefined variable references +4. **Consider Service Programs**: Convert to service programs for better reusability +5. **Add Comprehensive Error Handling**: Implement proper error codes and logging + +## Automation Tools & Best Practices + +### ๐Ÿ”ง Dependency Scanner Script + +A PowerShell/Shell script to automatically analyze COBOL dependencies: + +> ๐Ÿ“ **Available in:** [`tools/dependency-scanner.ps1`](tools/dependency-scanner.ps1) + +```powershell +# dependency-scanner.ps1 - Automated COBOL Dependency Analysis +param( + [string]$SourcePath = ".", + [string]$OutputFormat = "markdown" +) + +# Usage examples: +.\dependency-scanner.ps1 -SourcePath "." -OutputFormat "json" +.\dependency-scanner.ps1 -SourcePath "." -OutputFormat "markdown" -OutputFile "report.md" +``` + +**Features:** +- Scans COBOL source files for program dependencies +- Extracts variable definitions and references +- Generates reports in multiple formats (Markdown, JSON, CSV) +- Creates Mermaid dependency diagrams +- Provides program statistics and metrics + +### ๐ŸŽฏ Code Quality Validation Tools + +#### Variable Reference Validator + +> ๐Ÿ“ **Available in:** [`tools/validate-variables.sh`](tools/validate-variables.sh) + +```bash +#!/bin/bash +# validate-variables.sh - Check for undefined variable references + +# Usage examples: +./validate-variables.sh *.CBLLE +./validate-variables.sh CALLER.CBLLE HERON.CBLLE +``` + +**Features:** +- Detects undefined variable references (like PLOCHA-DISPLAYED in CALLER.CBLLE) +- Checks for missing periods and syntax issues +- Validates comment alignment for fixed-format COBOL +- Identifies inconsistent indentation +- Provides actionable error reports with line numbers + +**Sample validation output for this project:** +``` +Validating: CALLER.CBLLE + โš ๏ธ UNDEFINED VARIABLE: PLOCHA-DISPLAYED (referenced at line: 15) + โŒ Found 1 undefined variable reference(s) +``` + +### ๐Ÿ“‹ Program Documentation Template + +> ๐Ÿ“ **Available in:** [`tools/PROGRAM-TEMPLATE.CBLLE`](tools/PROGRAM-TEMPLATE.CBLLE) + +Standardized COBOL program template following AS400 best practices: + +```cobol + * =============================================== + * PROGRAM: [PROGRAM-NAME] + * PURPOSE: [Brief description of program purpose] + * AUTHOR: [Developer name] + * DATE: [Creation date - YYYY-MM-DD] + * VERSION: [Version number - V1.0.0] + * =============================================== + * DEPENDENCIES: + * - Called Programs: [List external programs called] + * - Copybooks: [List copybooks included] + * - Files: [List files accessed] + * =============================================== + * PARAMETERS: + * INPUT: [List input parameters with descriptions] + * OUTPUT: [List output parameters with descriptions] + * =============================================== + * ERROR CODES: + * 0000 - Success + * 0001 - Invalid input parameters + * 0002 - Processing error + * =============================================== + + IDENTIFICATION DIVISION. + PROGRAM-ID. [PROGRAM-NAME]. + + WORKING-STORAGE SECTION. + 01 WS-PROGRAM-INFO. + 05 WS-PROGRAM-NAME PIC X(10) VALUE '[PROGRAM-NAME]'. + 05 WS-VERSION PIC X(8) VALUE 'V1.0.0'. + 05 WS-LAST-MODIFIED PIC X(10) VALUE '[DATE]'. + + 01 WS-ERROR-HANDLING. + 05 WS-ERROR-CODE PIC 9(4) VALUE ZERO. + 88 SUCCESS VALUE 0000. + 88 INVALID-INPUT VALUE 0001. + 05 WS-ERROR-MESSAGE PIC X(80) VALUE SPACES. + + PROCEDURE DIVISION. + 0000-MAIN-PROCESS. + PERFORM 1000-INITIALIZE + PERFORM 2000-MAIN-LOGIC + PERFORM 9000-TERMINATE + STOP RUN. +``` + +**Features:** +- Comprehensive documentation headers +- Standard error handling patterns +- Structured program flow (Initialize โ†’ Process โ†’ Terminate) +- Debug mode support +- Consistent variable naming conventions + +### ๐Ÿ—๏ธ AS400 Build Instructions + +> ๐Ÿ“ **Complete guide available in:** [`tools/BUILD_INSTRUCTIONS.md`](tools/BUILD_INSTRUCTIONS.md) + +#### Quick Compilation Commands +```bash +# Compile individual COBOL program +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) + +# Batch compilation for CallingExample project +CRTCBLMOD MODULE(MYLIB/CALLER) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(CALLER) +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) +CRTPGM PGM(MYLIB/CALLER) MODULE(MYLIB/CALLER) +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) +``` + +#### Build Dependencies Order +1. **HERON.CBLLE** - Compile first (called by others) +2. **CALLER.CBLLE, CALLER2.CBLLE** - Can compile after HERON +3. **NESTEDCALL.CBLLE** - Independent (contains nested HERON) + +**The complete build guide includes:** +- Individual and batch compilation commands +- CL program for automated builds +- JCL templates for z/OS environments +- Makefile for modern development workflows +- Deployment scripts and automation +- Error troubleshooting guide +- Performance optimization recommendations + +### ๐Ÿงช Unit Testing Framework + +#### Test Program Template +```cobol + IDENTIFICATION DIVISION. + PROGRAM-ID. TEST-HERON. + + WORKING-STORAGE SECTION. + 01 TEST-RESULTS. + 05 TESTS-RUN PIC 9(3) VALUE ZERO. + 05 TESTS-PASSED PIC 9(3) VALUE ZERO. + 05 TESTS-FAILED PIC 9(3) VALUE ZERO. + + 01 TEST-DATA. + 05 TEST-A PACKED-DECIMAL PIC S9(10)V9(5). + 05 TEST-B PACKED-DECIMAL PIC S9(10)V9(5). + 05 TEST-C PACKED-DECIMAL PIC S9(10)V9(5). + 05 TEST-AREA PACKED-DECIMAL PIC S9(10)V9(5). + 05 EXPECTED-AREA PACKED-DECIMAL PIC S9(10)V9(5). + + PROCEDURE DIVISION. + 0000-MAIN-TEST. + PERFORM 1000-TEST-VALID-TRIANGLE + PERFORM 1100-TEST-INVALID-TRIANGLE + PERFORM 1200-TEST-EDGE-CASES + PERFORM 9000-DISPLAY-RESULTS + STOP RUN. + + 1000-TEST-VALID-TRIANGLE. + * Test Case: Valid triangle (3,4,5) - Expected area: 6.0 + MOVE 3.0 TO TEST-A + MOVE 4.0 TO TEST-B + MOVE 5.0 TO TEST-C + MOVE 6.0 TO EXPECTED-AREA + CALL PROGRAM "HERON" USING TEST-A TEST-B TEST-C TEST-AREA + PERFORM 9100-VERIFY-RESULT. + + 1100-TEST-INVALID-TRIANGLE. + * Test Case: Invalid triangle (1,2,5) - Expected area: -1.0 + MOVE 1.0 TO TEST-A + MOVE 2.0 TO TEST-B + MOVE 5.0 TO TEST-C + MOVE -1.0 TO EXPECTED-AREA + CALL PROGRAM "HERON" USING TEST-A TEST-B TEST-C TEST-AREA + PERFORM 9100-VERIFY-RESULT. + + 9100-VERIFY-RESULT. + ADD 1 TO TESTS-RUN + IF TEST-AREA = EXPECTED-AREA + ADD 1 TO TESTS-PASSED + DISPLAY "PASS: " TEST-A " " TEST-B " " TEST-C + " => " TEST-AREA + ELSE + ADD 1 TO TESTS-FAILED + DISPLAY "FAIL: " TEST-A " " TEST-B " " TEST-C + " Expected: " EXPECTED-AREA + " Actual: " TEST-AREA + END-IF. +``` + +### ๐Ÿ“Š Performance Optimization Guidelines + +#### Memory Usage Optimization +```cobol +* Use PACKED-DECIMAL for numeric calculations (AS400 optimized) +01 EFFICIENT-NUMERIC PACKED-DECIMAL PIC S9(10)V9(5). + +* Avoid unnecessary data movements +* Use COMPUTATIONAL fields for intermediate calculations +01 CALC-FIELD PIC S9(9) COMP. + +* Initialize variables efficiently +INITIALIZE WS-WORK-AREA. +* Instead of individual MOVE ZERO statements +``` + +#### Call Performance Best Practices +```cobol +* Use static calls when possible (compile-time binding) +CALL 'HERON' USING A B C AREA. + +* Minimize parameter passing overhead +* Group related parameters in data structures +01 TRIANGLE-PARAMS. + 05 SIDE-A PACKED-DECIMAL PIC S9(10)V9(5). + 05 SIDE-B PACKED-DECIMAL PIC S9(10)V9(5). + 05 SIDE-C PACKED-DECIMAL PIC S9(10)V9(5). + 05 CALCULATED-AREA PACKED-DECIMAL PIC S9(10)V9(5). + +CALL 'HERON' USING TRIANGLE-PARAMS. +``` + +### ๐Ÿ”„ Migration Roadmap & Timeline + +#### Phase 1: Immediate Improvements (1-2 weeks) +- [ ] Fix undefined variable references +- [ ] Implement standardized naming conventions +- [ ] Add error handling patterns +- [ ] Create program documentation headers + +#### Phase 2: Code Quality Enhancement (2-4 weeks) +- [ ] Introduce copybooks for shared data structures +- [ ] Implement unit testing framework +- [ ] Add comprehensive error codes +- [ ] Create build automation scripts + +#### Phase 3: Modernization (4-8 weeks) +- [ ] Convert to service programs where appropriate +- [ ] Implement logging and monitoring +- [ ] Add performance profiling +- [ ] Create integration interfaces + +#### Phase 4: Advanced Features (8-12 weeks) +- [ ] Implement continuous integration +- [ ] Add automated testing pipeline +- [ ] Create documentation generation tools +- [ ] Implement code quality metrics dashboard + +### ๐Ÿ›ก๏ธ Security Best Practices + +```cobol +* Input validation example +PROCEDURE DIVISION USING INPUT-PARAMS. + PERFORM 1000-VALIDATE-INPUT + IF VALID-INPUT + PERFORM 2000-PROCESS-REQUEST + ELSE + PERFORM 9000-HANDLE-ERROR + END-IF. + +1000-VALIDATE-INPUT. +* Validate numeric ranges + IF A <= 0 OR B <= 0 OR C <= 0 + SET INVALID-INPUT TO TRUE + MOVE "Invalid triangle dimensions" TO ERROR-MESSAGE + END-IF. + +* Validate data types and bounds + IF A > 999999.99999 OR B > 999999.99999 OR C > 999999.99999 + SET INVALID-INPUT TO TRUE + MOVE "Triangle dimensions too large" TO ERROR-MESSAGE + END-IF. +``` + +### ๐Ÿ“ˆ Code Quality Metrics + +#### Recommended Quality Gates +- **Cyclomatic Complexity**: < 10 per program +- **Lines of Code**: < 500 per program +- **Comment Ratio**: > 20% meaningful comments +- **Test Coverage**: > 80% of code paths +- **Code Duplication**: < 5% duplicate code blocks + +#### Quality Checklist +- [ ] All variables properly defined +- [ ] Consistent naming conventions used +- [ ] Error handling implemented +- [ ] Input validation present +- [ ] Documentation headers complete +- [ ] Unit tests created +- [ ] Performance considerations addressed + +--- + +*Generated on: 2025-07-21* +*Analyzed Programs: CALLER.CBLLE, CALLER2.CBLLE, HERON.CBLLE, NESTEDCALL.CBLLE* +*Analysis Type: Static code analysis and dependency mapping* +*Enhanced with: Automation tools, testing framework, and best practices* \ No newline at end of file diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/BUILD_INSTRUCTIONS.md b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/BUILD_INSTRUCTIONS.md new file mode 100644 index 0000000..836df4b --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/BUILD_INSTRUCTIONS.md @@ -0,0 +1,240 @@ +# AS400 COBOL Build and Deployment Guide + +## Prerequisites +- AS400/IBM i system access +- COBOL compiler (ILE COBOL) +- Source physical files (QCBLLESRC) +- Appropriate library permissions + +## Basic Compilation Commands + +### Individual Program Compilation +```bash +# Create COBOL module +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) + +# Create program object +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) +``` + +### Batch Compilation +```bash +# Compile all programs in the CallingExample project +CRTCBLMOD MODULE(MYLIB/CALLER) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(CALLER) +CRTCBLMOD MODULE(MYLIB/CALLER2) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(CALLER2) +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) +CRTCBLMOD MODULE(MYLIB/NESTEDCALL) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(NESTEDCALL) + +CRTPGM PGM(MYLIB/CALLER) MODULE(MYLIB/CALLER) +CRTPGM PGM(MYLIB/CALLER2) MODULE(MYLIB/CALLER2) +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) +CRTPGM PGM(MYLIB/NESTEDCALL) MODULE(MYLIB/NESTEDCALL) +``` + +### Compilation with Debug Information +```bash +# Compile with debug and event file +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) + OPTION(*EVENTF) DBGVIEW(*SOURCE) + +# Create program with debug info +CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) + OPTION(*DUPPROC) ALWUPD(*YES) +``` + +### Compilation with Optimization +```bash +# Optimize for performance +CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) + OPTIMIZE(40) OPTION(*EVENTF) +``` + +## CL Program for Automated Build + +```cobol +PGM +DCL VAR(&LIBRARY) TYPE(*CHAR) LEN(10) VALUE('COBOLDEM') +DCL VAR(&SRCFILE) TYPE(*CHAR) LEN(10) VALUE('QCBLLESRC') + +/* Create library if it doesn't exist */ +MONMSG MSGID(CPF2111) EXEC(CRTLIB LIB(&LIBRARY)) + +/* Compile HERON first (it's called by others) */ +CRTCBLMOD MODULE(&LIBRARY/HERON) SRCFILE(&LIBRARY/&SRCFILE) SRCMBR(HERON) +CRTPGM PGM(&LIBRARY/HERON) MODULE(&LIBRARY/HERON) + +/* Compile calling programs */ +CRTCBLMOD MODULE(&LIBRARY/CALLER) SRCFILE(&LIBRARY/&SRCFILE) SRCMBR(CALLER) +CRTPGM PGM(&LIBRARY/CALLER) MODULE(&LIBRARY/CALLER) + +CRTCBLMOD MODULE(&LIBRARY/CALLER2) SRCFILE(&LIBRARY/&SRCFILE) SRCMBR(CALLER2) +CRTPGM PGM(&LIBRARY/CALLER2) MODULE(&LIBRARY/CALLER2) + +CRTCBLMOD MODULE(&LIBRARY/NESTEDCALL) SRCFILE(&LIBRARY/&SRCFILE) SRCMBR(NESTEDCALL) +CRTPGM PGM(&LIBRARY/NESTEDCALL) MODULE(&LIBRARY/NESTEDCALL) + +SNDPGMMSG MSG('Build completed for CallingExample project') + +ENDPGM +``` + +## JCL Template for z/OS + +```jcl +//COBOLCMP JOB CLASS=A,MSGCLASS=X,NOTIFY=&SYSUID,TIME=10 +//* +//* COBOL Compilation JCL for CallingExample Programs +//* +//STEP1 EXEC PGM=IGYCRCTL,PARM='LIB,APOST,NODYNAM' +//STEPLIB DD DSN=SYS1.COBOL.COMPILER,DISP=SHR +//SYSLIB DD DSN=SYS1.COBOL.COPYLIB,DISP=SHR +// DD DSN=YOUR.COPYBOOK.LIBRARY,DISP=SHR +//SYSIN DD DSN=YOUR.SOURCE.LIBRARY(HERON),DISP=SHR +//SYSPRINT DD SYSOUT=* +//SYSOUT DD SYSOUT=* +//SYSOBJ DD DSN=YOUR.OBJECT.LIBRARY(HERON),DISP=(NEW,CATLG,DELETE), +// UNIT=SYSDA,SPACE=(CYL,(1,1)), +// DCB=(RECFM=FB,LRECL=80,BLKSIZE=800) +//* +//STEP2 EXEC PGM=IGYCRCTL,PARM='LIB,APOST,NODYNAM' +//STEPLIB DD DSN=SYS1.COBOL.COMPILER,DISP=SHR +//SYSLIB DD DSN=SYS1.COBOL.COPYLIB,DISP=SHR +// DD DSN=YOUR.COPYBOOK.LIBRARY,DISP=SHR +//SYSIN DD DSN=YOUR.SOURCE.LIBRARY(CALLER),DISP=SHR +//SYSPRINT DD SYSOUT=* +//SYSOUT DD SYSOUT=* +//SYSOBJ DD DSN=YOUR.OBJECT.LIBRARY(CALLER),DISP=(NEW,CATLG,DELETE), +// UNIT=SYSDA,SPACE=(CYL,(1,1)), +// DCB=(RECFM=FB,LRECL=80,BLKSIZE=800) +``` + +## Makefile for Modern Development + +```makefile +# Makefile for AS400 COBOL CallingExample +LIBRARY = COBOLDEM +SRCFILE = QCBLLESRC + +# Program dependencies +PROGRAMS = CALLER CALLER2 HERON NESTEDCALL +MODULES = $(addprefix $(LIBRARY)/, $(PROGRAMS)) + +.PHONY: all clean compile test + +all: compile + +compile: $(PROGRAMS) + +HERON: + CRTCBLMOD MODULE($(LIBRARY)/HERON) SRCFILE($(LIBRARY)/$(SRCFILE)) SRCMBR(HERON) + CRTPGM PGM($(LIBRARY)/HERON) MODULE($(LIBRARY)/HERON) + +CALLER: HERON + CRTCBLMOD MODULE($(LIBRARY)/CALLER) SRCFILE($(LIBRARY)/$(SRCFILE)) SRCMBR(CALLER) + CRTPGM PGM($(LIBRARY)/CALLER) MODULE($(LIBRARY)/CALLER) + +CALLER2: HERON + CRTCBLMOD MODULE($(LIBRARY)/CALLER2) SRCFILE($(LIBRARY)/$(SRCFILE)) SRCMBR(CALLER2) + CRTPGM PGM($(LIBRARY)/CALLER2) MODULE($(LIBRARY)/CALLER2) + +NESTEDCALL: + CRTCBLMOD MODULE($(LIBRARY)/NESTEDCALL) SRCFILE($(LIBRARY)/$(SRCFILE)) SRCMBR(NESTEDCALL) + CRTPGM PGM($(LIBRARY)/NESTEDCALL) MODULE($(LIBRARY)/NESTEDCALL) + +clean: + DLTPGM PGM($(LIBRARY)/CALLER) + DLTPGM PGM($(LIBRARY)/CALLER2) + DLTPGM PGM($(LIBRARY)/HERON) + DLTPGM PGM($(LIBRARY)/NESTEDCALL) + DLTMOD MODULE($(LIBRARY)/CALLER) + DLTMOD MODULE($(LIBRARY)/CALLER2) + DLTMOD MODULE($(LIBRARY)/HERON) + DLTMOD MODULE($(LIBRARY)/NESTEDCALL) + +test: + CALL PGM($(LIBRARY)/CALLER) + CALL PGM($(LIBRARY)/CALLER2) + CALL PGM($(LIBRARY)/NESTEDCALL) +``` + +## Deployment Script + +```bash +#!/bin/bash +# deploy.sh - Deploy COBOL programs to AS400 + +LIBRARY="COBOLDEM" +AS400_USER="youruser" +AS400_HOST="your.as400.system" + +echo "Deploying CallingExample to AS400..." + +# Upload source files +ftp -n $AS400_HOST << EOF +user $AS400_USER +binary +put CALLER.CBLLE "CALLER" +put CALLER2.CBLLE "CALLER2" +put HERON.CBLLE "HERON" +put NESTEDCALL.CBLLE "NESTEDCALL" +quit +EOF + +# Remote compilation +ssh $AS400_USER@$AS400_HOST << EOF +CRTCBLMOD MODULE($LIBRARY/HERON) SRCFILE($LIBRARY/QCBLLESRC) SRCMBR(HERON) +CRTPGM PGM($LIBRARY/HERON) MODULE($LIBRARY/HERON) + +CRTCBLMOD MODULE($LIBRARY/CALLER) SRCFILE($LIBRARY/QCBLLESRC) SRCMBR(CALLER) +CRTPGM PGM($LIBRARY/CALLER) MODULE($LIBRARY/CALLER) + +CRTCBLMOD MODULE($LIBRARY/CALLER2) SRCFILE($LIBRARY/QCBLLESRC) SRCMBR(CALLER2) +CRTPGM PGM($LIBRARY/CALLER2) MODULE($LIBRARY/CALLER2) + +CRTCBLMOD MODULE($LIBRARY/NESTEDCALL) SRCFILE($LIBRARY/QCBLLESRC) SRCMBR(NESTEDCALL) +CRTPGM PGM($LIBRARY/NESTEDCALL) MODULE($LIBRARY/NESTEDCALL) +EOF + +echo "Deployment completed!" +``` + +## Common Compilation Errors and Solutions + +### Error: Program not found +``` +Solution: Ensure the called program (HERON) is compiled first +Command: CRTCBLMOD MODULE(MYLIB/HERON) SRCFILE(MYLIB/QCBLLESRC) SRCMBR(HERON) + CRTPGM PGM(MYLIB/HERON) MODULE(MYLIB/HERON) +``` + +### Error: Undefined variable +``` +Solution: Fix variable references in source code +- CALLER.CBLLE line 15: Change PLOCHA-DISPLAYED to AREA-DISP +- NESTEDCALL.CBLLE line 13-14: Change PLOCHA to AREA +``` + +### Error: Source member not found +``` +Solution: Ensure source files are properly uploaded to QCBLLESRC +Command: CPYFRMSTMF FROMSTMF('/path/to/HERON.CBLLE') + TOMBR('/QSYS.LIB/MYLIB.LIB/QCBLLESRC.FILE/HERON.MBR') +``` + +## Performance Optimization Tips + +1. **Use PACKED-DECIMAL for calculations** + - Already implemented in CallingExample + - Optimal for AS400 processors + +2. **Minimize parameter passing** + - Group related parameters + - Use BY REFERENCE when possible + +3. **Optimize CALL statements** + - Use static calls for better performance + - Consider service programs for frequently called routines + +4. **Compiler optimization** + - Use OPTIMIZE(40) for production builds + - Enable optimization for mathematical operations \ No newline at end of file diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/PROGRAM-TEMPLATE.CBLLE b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/PROGRAM-TEMPLATE.CBLLE new file mode 100644 index 0000000..ef62066 --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/PROGRAM-TEMPLATE.CBLLE @@ -0,0 +1,171 @@ + * =============================================== + * PROGRAM: [PROGRAM-NAME] + * PURPOSE: [Brief description of program purpose] + * AUTHOR: [Developer name] + * DATE: [Creation date - YYYY-MM-DD] + * VERSION: [Version number - V1.0.0] + * =============================================== + * DEPENDENCIES: + * - Called Programs: [List external programs called] + * - Copybooks: [List copybooks included] + * - Files: [List files accessed] + * - Libraries: [List service programs used] + * =============================================== + * PARAMETERS: + * INPUT: + * [PARAM-NAME] - [Data Type] - [Description] + * OUTPUT: + * [PARAM-NAME] - [Data Type] - [Description] + * IN/OUT: + * [PARAM-NAME] - [Data Type] - [Description] + * =============================================== + * ERROR CODES: + * 0000 - Success + * 0001 - Invalid input parameters + * 0002 - Processing error + * [Add more as needed] + * =============================================== + * BUSINESS LOGIC: + * [Brief description of the business logic implemented] + * [Include any special algorithms or formulas used] + * =============================================== + * REVISION HISTORY: + * [Date] [Author] [Description of changes] + * [YYYY-MM-DD] [Initial Dev] [Initial creation] + * =============================================== + + IDENTIFICATION DIVISION. + PROGRAM-ID. [PROGRAM-NAME]. + AUTHOR. [DEVELOPER-NAME]. + DATE-WRITTEN. [CREATION-DATE]. + DATE-COMPILED. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + SOURCE-COMPUTER. IBM-AS400. + OBJECT-COMPUTER. IBM-AS400. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + * Program identification and version info + 01 WS-PROGRAM-INFO. + 05 WS-PROGRAM-NAME PIC X(10) VALUE '[PROGRAM-NAME]'. + 05 WS-VERSION PIC X(8) VALUE 'V1.0.0'. + 05 WS-LAST-MODIFIED PIC X(10) VALUE '[YYYY-MM-DD]'. + 05 WS-AUTHOR PIC X(20) VALUE '[AUTHOR-NAME]'. + + * Error handling variables + 01 WS-ERROR-HANDLING. + 05 WS-ERROR-CODE PIC 9(4) VALUE ZERO. + 88 SUCCESS VALUE 0000. + 88 INVALID-INPUT VALUE 0001. + 88 PROCESSING-ERROR VALUE 0002. + 05 WS-ERROR-MESSAGE PIC X(80) VALUE SPACES. + 05 WS-DEBUG-MODE PIC X(1) VALUE 'N'. + 88 DEBUG-ON VALUE 'Y'. + 88 DEBUG-OFF VALUE 'N'. + + * Processing control variables + 01 WS-CONTROL-FLAGS. + 05 WS-FIRST-TIME PIC X(1) VALUE 'Y'. + 88 FIRST-TIME VALUE 'Y'. + 88 NOT-FIRST-TIME VALUE 'N'. + 05 WS-END-OF-PROGRAM PIC X(1) VALUE 'N'. + 88 END-OF-PROGRAM VALUE 'Y'. + 88 NOT-END-OF-PROGRAM VALUE 'N'. + + * Work variables - customize as needed + 01 WS-WORK-VARIABLES. + 05 WS-COUNTER PIC 9(5) VALUE ZERO. + 05 WS-TEMP-FIELD PIC X(100) VALUE SPACES. + + * [Add your specific working storage variables here] + + * LINKAGE SECTION - Uncomment if this is a called program + * LINKAGE SECTION. + * 01 LS-INPUT-PARAMETERS. + * 05 LS-PARAM1 PIC X(10). + * 05 LS-PARAM2 PIC 9(5). + * 01 LS-OUTPUT-PARAMETERS. + * 05 LS-RESULT PIC X(20). + + PROCEDURE DIVISION. + * PROCEDURE DIVISION USING LS-INPUT-PARAMETERS LS-OUTPUT-PARAMETERS. + + 0000-MAIN-PROCESS. + * Main processing routine + PERFORM 1000-INITIALIZE + IF SUCCESS + PERFORM 2000-MAIN-LOGIC + END-IF + PERFORM 9000-TERMINATE + STOP RUN. + + 1000-INITIALIZE. + * Program initialization + IF DEBUG-ON + DISPLAY 'Starting program: ' WS-PROGRAM-NAME + ' Version: ' WS-VERSION + END-IF + + SET NOT-FIRST-TIME TO TRUE + + * Add initialization logic here + CONTINUE. + + 2000-MAIN-LOGIC. + * Main business logic + EVALUATE TRUE + WHEN FIRST-TIME + PERFORM 2100-FIRST-TIME-PROCESSING + WHEN OTHER + PERFORM 2200-STANDARD-PROCESSING + END-EVALUATE. + + 2100-FIRST-TIME-PROCESSING. + * First time processing logic + CONTINUE. + + 2200-STANDARD-PROCESSING. + * Standard processing logic + CONTINUE. + + 8000-ERROR-HANDLING. + * Centralized error handling + EVALUATE WS-ERROR-CODE + WHEN 0001 + MOVE 'Invalid input parameters provided' + TO WS-ERROR-MESSAGE + WHEN 0002 + MOVE 'Processing error occurred' + TO WS-ERROR-MESSAGE + WHEN OTHER + MOVE 'Unknown error occurred' + TO WS-ERROR-MESSAGE + END-EVALUATE + + DISPLAY 'ERROR ' WS-ERROR-CODE ': ' WS-ERROR-MESSAGE + + IF DEBUG-ON + DISPLAY 'Program: ' WS-PROGRAM-NAME + DISPLAY 'Error location: [Specify where error occurred]' + END-IF. + + 9000-TERMINATE. + * Program cleanup and termination + IF DEBUG-ON + DISPLAY 'Ending program: ' WS-PROGRAM-NAME + DISPLAY 'Final status: ' WS-ERROR-CODE + END-IF + + IF NOT SUCCESS + PERFORM 8000-ERROR-HANDLING + END-IF + + * Add cleanup logic here + CONTINUE. + + * =============================================== + * END OF PROGRAM TEMPLATE + * =============================================== \ No newline at end of file diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/README.md b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/README.md new file mode 100644 index 0000000..cd74df3 --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/README.md @@ -0,0 +1,188 @@ +# COBOL Development Tools + +This directory contains automation tools and templates to streamline COBOL development and maintenance for the CallingExample project. + +## ๐Ÿ”ง Available Tools + +### 1. Dependency Scanner (`dependency-scanner.ps1`) +PowerShell script for automated COBOL dependency analysis. + +**Features:** +- Scans COBOL source files for program dependencies +- Extracts variable definitions and references +- Generates reports in multiple formats (Markdown, JSON, CSV) +- Creates Mermaid dependency diagrams + +**Usage:** +```powershell +# Basic scan with markdown output +.\dependency-scanner.ps1 -SourcePath ".." -OutputFormat "markdown" + +# Export to JSON file +.\dependency-scanner.ps1 -SourcePath ".." -OutputFormat "json" -OutputFile "dependencies.json" + +# Export to CSV for analysis +.\dependency-scanner.ps1 -SourcePath ".." -OutputFormat "csv" -OutputFile "dependencies.csv" +``` + +### 2. Variable Validator (`validate-variables.sh`) +Bash script for checking undefined variable references and code quality issues. + +**Features:** +- Detects undefined variable references +- Checks for missing periods +- Validates comment alignment +- Identifies inconsistent indentation +- Comprehensive code quality analysis + +**Usage:** +```bash +# Validate all COBOL files +./validate-variables.sh *.CBLLE + +# Validate specific files +./validate-variables.sh CALLER.CBLLE HERON.CBLLE + +# Check single program +./validate-variables.sh HERON.CBLLE +``` + +**Sample Output:** +``` +COBOL Variable Reference Validator +================================== + +Validating: CALLER.CBLLE +------------ + โš ๏ธ UNDEFINED VARIABLE: PLOCHA-DISPLAYED (referenced at lines: 15) + โŒ Found 1 undefined variable reference(s) + +Additional Code Quality Checks: + โš ๏ธ Potential missing periods: 2 lines +``` + +### 3. Program Template (`PROGRAM-TEMPLATE.CBLLE`) +Standardized COBOL program template following AS400 best practices. + +**Features:** +- Comprehensive documentation headers +- Standard error handling patterns +- Structured program flow (Initialize โ†’ Process โ†’ Terminate) +- Debug mode support +- Consistent variable naming conventions + +**Usage:** +1. Copy template to new program file +2. Replace placeholders with actual values: + - `[PROGRAM-NAME]` โ†’ Your program name + - `[DEVELOPER-NAME]` โ†’ Your name + - `[CREATION-DATE]` โ†’ Current date + - `[Brief description]` โ†’ Program purpose +3. Add your specific business logic in appropriate sections + +## ๐Ÿ“– Documentation + +### Build Instructions (`BUILD_INSTRUCTIONS.md`) +Comprehensive guide for compiling and deploying COBOL programs on AS400. + +**Includes:** +- Individual and batch compilation commands +- CL program for automated builds +- JCL templates for z/OS +- Makefile for modern development +- Deployment scripts +- Common error solutions +- Performance optimization tips + +## ๐Ÿš€ Quick Start + +1. **Validate existing code:** + ```bash + cd /path/to/QCBLLESRC + ./tools/validate-variables.sh *.CBLLE + ``` + +2. **Generate dependency report:** + ```powershell + cd /path/to/QCBLLESRC + .\tools\dependency-scanner.ps1 -SourcePath "." -OutputFormat "markdown" -OutputFile "current-dependencies.md" + ``` + +3. **Create new program from template:** + ```bash + cp tools/PROGRAM-TEMPLATE.CBLLE NEW-PROGRAM.CBLLE + # Edit NEW-PROGRAM.CBLLE and replace placeholders + ``` + +4. **Build programs:** + ```bash + # Follow instructions in tools/BUILD_INSTRUCTIONS.md + ``` + +## ๐ŸŽฏ Integration with Development Workflow + +### Pre-commit Validation +Add to your development process: +```bash +#!/bin/bash +# pre-commit-hook.sh +echo "Running COBOL validation..." +if ./tools/validate-variables.sh *.CBLLE; then + echo "โœ… All validations passed" + exit 0 +else + echo "โŒ Validation failed - please fix issues before committing" + exit 1 +fi +``` + +### Continuous Integration +Example CI/CD pipeline step: +```yaml +- name: Validate COBOL Code + run: | + cd AS400/COBOL_examples/CallingExample/QCBLLESRC + ./tools/validate-variables.sh *.CBLLE + +- name: Generate Dependency Report + run: | + cd AS400/COBOL_examples/CallingExample/QCBLLESRC + pwsh -File tools/dependency-scanner.ps1 -SourcePath "." -OutputFormat "json" -OutputFile "build-artifacts/dependencies.json" +``` + +## ๐Ÿ”„ Tool Enhancement Ideas + +### Future Improvements +1. **Performance Profiler**: Tool to analyze COBOL program performance +2. **Copybook Generator**: Extract common data structures into copybooks +3. **Code Metrics Dashboard**: Visual representation of code quality metrics +4. **Migration Assistant**: Help migrate legacy patterns to modern COBOL +5. **Test Generator**: Automatically create unit tests from program specifications +6. **Documentation Generator**: Extract documentation from source code comments + +### Contributing +To add new tools or enhance existing ones: +1. Follow the established naming conventions +2. Add comprehensive documentation +3. Include usage examples +4. Test thoroughly with the CallingExample programs +5. Update this README with new tool information + +## ๐Ÿ“‹ Tool Requirements + +### Dependencies +- **PowerShell 5.1+** (for dependency-scanner.ps1) +- **Bash** (for validate-variables.sh) +- **AS400/IBM i system** (for build instructions) +- **COBOL compiler** (ILE COBOL recommended) + +### Permissions +- Read access to COBOL source files +- Write access for output files +- AS400 system access for compilation and deployment + +--- + +*Last Updated: 2025-07-21* +*Tool Version: v1.0.0* +*Supports: AS400 COBOL, ILE COBOL* \ No newline at end of file diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/dependency-scanner.ps1 b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/dependency-scanner.ps1 new file mode 100644 index 0000000..061fd5e --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/dependency-scanner.ps1 @@ -0,0 +1,182 @@ +# dependency-scanner.ps1 - Automated COBOL Dependency Analysis +# Usage: .\dependency-scanner.ps1 -SourcePath "QCBLLESRC" -OutputFormat "json" + +param( + [string]$SourcePath = ".", + [string]$OutputFormat = "markdown", # Options: markdown, json, csv + [string]$OutputFile = "" +) + +function Scan-CobolDependencies { + param([string]$Path) + + Write-Host "Scanning COBOL dependencies in: $Path" -ForegroundColor Green + + $programs = Get-ChildItem -Path $Path -Filter "*.CBLLE" -Recurse + $dependencies = @() + $programInfo = @{} + + foreach ($program in $programs) { + $content = Get-Content $program.FullName + $programName = ($program.BaseName).ToUpper() + $lineCount = $content.Length + + Write-Host " Analyzing: $programName ($lineCount lines)" -ForegroundColor Cyan + + # Store program info + $programInfo[$programName] = @{ + FileName = $program.Name + LineCount = $lineCount + Path = $program.FullName + } + + # Extract CALL statements + $calls = $content | Select-String -Pattern 'CALL\s+(PROGRAM\s+)?"([^"]+)"' -AllMatches + foreach ($call in $calls) { + $calledProgram = $call.Matches[0].Groups[2].Value + $dependencies += [PSCustomObject]@{ + Caller = $programName + Called = $calledProgram.ToUpper() + Type = if ($call.Matches[0].Groups[1].Value) { "External" } else { "Nested" } + Line = $call.LineNumber + Statement = $call.Line.Trim() + } + } + + # Extract variable definitions + $variables = $content | Select-String -Pattern '^\s*[0-9]{2}\s+([A-Z0-9-]+)\s+' -AllMatches + $programInfo[$programName].Variables = @() + foreach ($var in $variables) { + $varName = $var.Matches[0].Groups[1].Value + $programInfo[$programName].Variables += [PSCustomObject]@{ + Name = $varName + Line = $var.LineNumber + Definition = $var.Line.Trim() + } + } + } + + return @{ + Dependencies = $dependencies + Programs = $programInfo + ScanTime = Get-Date + } +} + +function Export-Results { + param( + [object]$Results, + [string]$Format, + [string]$OutputFile + ) + + switch ($Format.ToLower()) { + "json" { + $jsonOutput = $Results | ConvertTo-Json -Depth 4 + if ($OutputFile) { + $jsonOutput | Out-File $OutputFile -Encoding UTF8 + Write-Host "Results exported to: $OutputFile" -ForegroundColor Green + } else { + Write-Output $jsonOutput + } + } + "csv" { + $csvFile = if ($OutputFile) { $OutputFile } else { "dependencies.csv" } + $Results.Dependencies | Export-Csv $csvFile -NoTypeInformation + Write-Host "Dependencies exported to: $csvFile" -ForegroundColor Green + } + "markdown" { + $mdOutput = Generate-MarkdownReport $Results + if ($OutputFile) { + $mdOutput | Out-File $OutputFile -Encoding UTF8 + Write-Host "Markdown report exported to: $OutputFile" -ForegroundColor Green + } else { + Write-Output $mdOutput + } + } + default { + Write-Error "Unsupported output format: $Format" + } + } +} + +function Generate-MarkdownReport { + param([object]$Results) + + $report = @" +# COBOL Dependency Analysis Report + +**Generated:** $($Results.ScanTime) + +## Program Summary + +| Program | Lines | Variables | Calls Made | +|---------|-------|-----------|------------| +"@ + + foreach ($program in $Results.Programs.Keys) { + $info = $Results.Programs[$program] + $callsMade = ($Results.Dependencies | Where-Object { $_.Caller -eq $program }).Count + $report += "`n| $program | $($info.LineCount) | $($info.Variables.Count) | $callsMade |" + } + + $report += @" + +## Dependencies + +| Caller | Called | Type | Line | Statement | +|--------|--------|------|------|-----------| +"@ + + foreach ($dep in $Results.Dependencies) { + $report += "`n| $($dep.Caller) | $($dep.Called) | $($dep.Type) | $($dep.Line) | ``$($dep.Statement)`` |" + } + + # Generate Mermaid diagram + $report += @" + +## Dependency Diagram + +``````mermaid +graph TB +"@ + + $nodeId = 65 # Start with 'A' + $nodeMap = @{} + + # Create nodes for all programs + foreach ($program in $Results.Programs.Keys) { + $nodeChar = [char]$nodeId + $nodeMap[$program] = $nodeChar + $report += "`n $nodeChar[$program]" + $nodeId++ + } + + # Add dependencies + foreach ($dep in $Results.Dependencies) { + $callerNode = $nodeMap[$dep.Caller] + $calledNode = $nodeMap[$dep.Called] + if ($calledNode) { + $report += "`n $callerNode -->|$($dep.Type)| $calledNode" + } + } + + $report += "`n``````" + + return $report +} + +# Main execution +try { + $results = Scan-CobolDependencies -Path $SourcePath + + Write-Host "`nScan Complete!" -ForegroundColor Green + Write-Host " Programs found: $($results.Programs.Count)" -ForegroundColor Yellow + Write-Host " Dependencies found: $($results.Dependencies.Count)" -ForegroundColor Yellow + + Export-Results -Results $results -Format $OutputFormat -OutputFile $OutputFile + +} catch { + Write-Error "Error during scan: $($_.Exception.Message)" + exit 1 +} \ No newline at end of file diff --git a/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/validate-variables.sh b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/validate-variables.sh new file mode 100755 index 0000000..5d04b2d --- /dev/null +++ b/AS400/COBOL_examples/CallingExample/QCBLLESRC/tools/validate-variables.sh @@ -0,0 +1,119 @@ +#!/bin/bash +# validate-variables.sh - Check for undefined variable references in COBOL programs +# Usage: ./validate-variables.sh [file1.CBLLE] [file2.CBLLE] ... +# ./validate-variables.sh *.CBLLE + +echo "COBOL Variable Reference Validator" +echo "==================================" + +validate_cobol_variables() { + local file="$1" + echo "" + echo "Validating: $file" + echo "$(printf '%*s' "${#file}" | tr ' ' '-')" + + if [[ ! -f "$file" ]]; then + echo "ERROR: File not found: $file" + return 1 + fi + + # Extract defined variables (level 01, 77, etc.) + # Look for lines starting with whitespace, followed by level number, then variable name + defined_vars=$(grep -E "^\s*(01|77|[0-9]{2})\s+([A-Z0-9-]+)" "$file" | \ + sed -E 's/^\s*[0-9]{2}\s+([A-Z0-9-]+).*/\1/' | \ + sort -u) + + # Extract referenced variables in various statements + # MOVE, DISPLAY, COMPUTE, ADD, SUBTRACT, etc. + referenced_vars=$(grep -iE "(MOVE|DISPLAY|COMPUTE|ADD|SUBTRACT|MULTIPLY|DIVIDE)\s+" "$file" | \ + grep -oE "\b[A-Z0-9-]+\b" | \ + grep -E "^[A-Z]" | \ + sort -u) + + # Find undefined references + undefined_count=0 + for var in $referenced_vars; do + # Skip COBOL reserved words and keywords + if [[ "$var" =~ ^(TO|FROM|BY|INTO|GIVING|USING|VALUE|PICTURE|PIC|PACKED-DECIMAL|COMP|DISPLAY|ZERO|ZEROS|SPACE|SPACES|LOW-VALUE|HIGH-VALUE|FUNCTION|SQRT|PROGRAM|CALL|GOBACK|STOP|RUN|IF|ELSE|END-IF|PERFORM|UNTIL|TIMES|VARYING)$ ]]; then + continue + fi + + # Skip numeric literals and string literals + if [[ "$var" =~ ^[0-9]+$ ]] || [[ "$var" =~ ^\".*\"$ ]]; then + continue + fi + + # Check if variable is defined + if ! echo "$defined_vars" | grep -q "^$var$"; then + line_nums=$(grep -n "\b$var\b" "$file" | cut -d: -f1 | tr '\n' ',' | sed 's/,$//') + echo " โš ๏ธ UNDEFINED VARIABLE: $var (referenced at lines: $line_nums)" + ((undefined_count++)) + fi + done + + if [[ $undefined_count -eq 0 ]]; then + echo " โœ… No undefined variable references found" + else + echo " โŒ Found $undefined_count undefined variable reference(s)" + fi + + # Additional checks + echo "" + echo "Additional Code Quality Checks:" + + # Check for missing periods + missing_periods=$(grep -n "^\s*[A-Z].*[^.]$" "$file" | grep -v "^\s*\*" | wc -l) + if [[ $missing_periods -gt 0 ]]; then + echo " โš ๏ธ Potential missing periods: $missing_periods lines" + fi + + # Check for inconsistent indentation + inconsistent_indent=$(grep -n "^[A-Z]" "$file" | grep -v "IDENTIFICATION\|PROGRAM-ID\|WORKING-STORAGE\|PROCEDURE\|LINKAGE" | wc -l) + if [[ $inconsistent_indent -gt 0 ]]; then + echo " โš ๏ธ Inconsistent indentation: $inconsistent_indent lines" + fi + + # Check for comments alignment (should start in column 7 for fixed format) + misaligned_comments=$(grep -n "^\s*\*" "$file" | grep -v "^\s\s\s\s\s\s\*" | wc -l) + if [[ $misaligned_comments -gt 0 ]]; then + echo " โš ๏ธ Misaligned comments: $misaligned_comments lines" + fi + + return $undefined_count +} + +# Main execution +total_errors=0 +files_processed=0 + +if [[ $# -eq 0 ]]; then + # If no arguments provided, scan all .CBLLE files in current directory + files=(*.CBLLE) + if [[ ! -f "${files[0]}" ]]; then + echo "No .CBLLE files found in current directory" + exit 1 + fi +else + files=("$@") +fi + +for file in "${files[@]}"; do + validate_cobol_variables "$file" + error_count=$? + total_errors=$((total_errors + error_count)) + files_processed=$((files_processed + 1)) +done + +echo "" +echo "======================================" +echo "Validation Summary:" +echo " Files processed: $files_processed" +echo " Total errors found: $total_errors" + +if [[ $total_errors -eq 0 ]]; then + echo " โœ… All files passed validation!" + exit 0 +else + echo " โŒ Issues found that need attention" + exit 1 +fi \ No newline at end of file