### Example 2: Getting First Characters Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/left_dollar.html Shows how to extract the first 5 characters from a string to get a greeting. ```vb6 Dim text As String text = "Hello, World!" greeting = Left$(text, 5) ' "Hello" ``` -------------------------------- ### VB6 Simple Partition Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/graphics/partition.html Demonstrates the basic usage of the Partition function to get a string representing a numerical range. Useful for categorizing single values into predefined bins. ```vb Dim range As String range = Partition(15, 0, 100, 10) ' Returns " 10: 19" range = Partition(5, 0, 100, 10) ' Returns " 0: 9" range = Partition(95, 0, 100, 10) ' Returns " 90: 99" ``` -------------------------------- ### Rust Example: Creating and Asserting PropertyGroup Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/common/properties.html Demonstrates how to create a PropertyGroup with a name, GUID, and properties, and then assert its values. This is useful for initializing and verifying property structures. ```rust use vb6parse::files::common::{PropertyGroup, Properties}; use vb6parse::language::Color; use vb6parse::language::color::VB_RED; use std::collections::HashMap; use either::Either; use uuid::Uuid; let mut properties = HashMap::new(); properties.insert("BackColor".to_string(), Either::Left(VB_RED.to_vb_string())); let group = PropertyGroup { name: "FormProperties".to_string(), guid: Some(Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap()), properties, }; assert_eq!(group.name, "FormProperties"); assert_eq!(group.guid.unwrap().to_string(), "123e4567-e89b-12d3-a456-426614174000"); assert_eq!(group.properties.get("BackColor").unwrap(), &Either::Left(VB_RED.to_vb_string())); ``` -------------------------------- ### Rust Example: PropertyGroup Initialization and Assertion Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/common/properties.html Shows how to initialize a PropertyGroup with a name, GUID, and properties, and then assert its properties. This is useful for setting up and verifying property data structures. ```rust use vb6parse::files::common::PropertyGroup; use vb6parse::language::Color; use vb6parse::language::color::VB_RED; use std::collections::HashMap; use either::Either; use uuid::Uuid; let mut properties = HashMap::new(); properties.insert("BackColor".to_string(), Either::Left(VB_RED.to_vb_string())); let group = PropertyGroup { name: "FormProperties".to_string(), guid: Some(Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000")?), properties, }; assert_eq!(group.name, "FormProperties"); assert_eq!(group.guid.expect("Expected GUID").to_string(), "123e4567-e89b-12d3-a456-426614174000"); ``` -------------------------------- ### Example 1: Extracting File Extension Prefix Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/left_dollar.html Demonstrates extracting the first 3 characters from a filename string to get a prefix. ```vb6 Dim filename As String filename = "document.txt" prefix = Left$(filename, 3) ' "doc" ``` -------------------------------- ### Get Fiscal Quarter (Custom Start Month) in VB.NET Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/month.html Calculates the fiscal quarter for a given date, allowing for a customizable start month for the fiscal year. For example, if fiscalStartMonth is 10 (October), then Oct-Dec is Q1. ```vb ' Pattern 4: Get fiscal quarter (Oct-Dec = Q1) Function GetFiscalQuarter(dateValue As Date, fiscalStartMonth As Integer) As Integer Dim monthNum As Integer Dim adjustedMonth As Integer monthNum = Month(dateValue) adjustedMonth = monthNum - fiscalStartMonth + 1 If adjustedMonth <= 0 Then adjustedMonth = adjustedMonth + 12 End If ' Integer division to get quarter (1-based) Dim fiscalQuarter As Integer fiscalQuarter = CInt(Int((adjustedMonth - 1) / 3)) + 1 GetFiscalQuarter = fiscalQuarter End Function ``` -------------------------------- ### GetSetting Basic Usage Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/environment/getsetting.html Demonstrates retrieving various types of settings from the Windows registry using GetSetting. Includes examples with and without default values. ```vbscript ' Example 1: Get a simple setting with default Dim userName As String userName = GetSetting("MyApp", "User", "Name", "Guest") ``` ```vbscript ' Example 2: Get window position Dim formLeft As String formLeft = GetSetting("MyApp", "Window", "Left", "0") ``` ```vbscript ' Example 3: Get setting without default Dim lastFile As String lastFile = GetSetting("MyApp", "Recent", "File1") ``` ```vbscript ' Example 4: Get database connection Dim connString As String connString = GetSetting("MyApp", "Database", "ConnectionString", "") ``` -------------------------------- ### VB6 Mid$ Function Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/string/mid_dollar.html Demonstrates extracting substrings using the Mid$ function. Use to get a portion of a string starting at a specific position, optionally for a defined length. ```vbscript Dim result As String result = Mid$("Hello World", 2, 3) ' Returns "ell" ``` ```vbscript result = Mid$("Hello World", 7) ' Returns "World" ``` ```vbscript result = Mid$("Hi", 10) ' Returns "" ``` -------------------------------- ### Load and Apply Settings Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/environment/getallsettings.html This example retrieves application settings and then iterates through them to apply specific configurations like theme and language based on the retrieved key-value pairs. ```vbscript Dim appSettings As Variant appSettings = GetAllSettings("MyApp", "Options") If Not IsEmpty(appSettings) Then Dim j As Long For j = 0 To UBound(appSettings, 1) Select Case appSettings(j, 0) Case "Theme" ApplyTheme appSettings(j, 1) Case "Language" SetLanguage appSettings(j, 1) End Select Next j End If ``` -------------------------------- ### VB6 Partition Out of Range Values Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/graphics/partition.html Shows how the Partition function handles values that fall outside the specified start and stop boundaries. Values below the start get a range ending before the start, and values above the stop get a range starting after the stop. ```vb Dim range As String range = Partition(-5, 0, 100, 10) ' Returns " : -1" (below start) range = Partition(150, 0, 100, 10) ' Returns "101: " (above stop) ``` -------------------------------- ### VB6Parse Development Setup Source: https://github.com/scriptandcompile/vb6parse/blob/master/README.md Commands to clone the repository, initialize submodules for test data, and run essential development tasks like tests, benchmarks, linting, and formatting. ```bash # Clone repository git clone https://github.com/scriptandcompile/vb6parse cd vb6parse # Get test data git submodule update --init --recursive # Run tests cargo test # Run benchmarks cargo bench # Check for issues cargo clippy # Format code cargo fmt ``` -------------------------------- ### Run a Cargo Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/README.md Execute a specific example provided with the cargo project. ```bash cargo run --example parse_project ``` -------------------------------- ### Rust Example: Instantiating ProjectProperties Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/project/properties.html This snippet shows how to create a ProjectProperties instance with various settings. It demonstrates setting properties like project name, startup mode, and compilation details. ```rust use vb6parse::files::project::properties::{ProjectProperties, StartMode, InteractionMode}; let project_props = ProjectProperties { unused_control_info: Default::default(), upgrade_controls: Default::default(), res_file_32_path: "path/to/resource.res", icon_form: "Form1", startup: "Sub Main", help_file_path: "helpfile.chm", title: "My VB6 Project", exe_32_file_name: "MyApp.exe", exe_32_compatible: "Yes", dll_base_address: 4194304, path_32: "C:\\MyProject", command_line_arguments: "", name: "MyProject", description: "A sample VB6 project", debug_startup_component: "Component1", help_context_id: "1000", compatibility_mode: Default::default(), version_32_compatibility: "Yes", version_info: Default::default(), server_support_files: Default::default(), conditional_compile: "", compilation_type: Default::default(), start_mode: StartMode::StandAlone, unattended: InteractionMode::Interactive, retained: Default::default(), thread_per_object: 1, threading_model: Default::default(), max_number_of_threads: 1, debug_startup_option: Default::default(), use_existing_browser: Default::default(), }; assert_eq!(project_props.name, "MyProject"); assert_eq!(project_props.start_mode, StartMode::StandAlone); ``` -------------------------------- ### VB.NET: Get Fiscal Year Start using DateSerial Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/dateserial.html Calculates the start date of a fiscal year given the calendar year and the starting month of the fiscal year. Assumes the start is the first day of the month. ```vb Function GetFiscalYearStart(calendarYear As Integer, fiscalStartMonth As Integer) As Date GetFiscalYearStart = DateSerial(calendarYear, fiscalStartMonth, 1) End Function ``` -------------------------------- ### Save Simple Setting Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/system_interaction/savesetting.html Demonstrates saving simple numeric settings for application startup position. Settings are stored as strings in the registry. ```vb SaveSetting "MyApp", "Startup", "Left", 100 SaveSetting "MyApp", "Startup", "Top", 100 ``` -------------------------------- ### JavaScript: Get Default VB6 Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/web_example.md Retrieves a default VB6 code example based on the selected file type. Used to populate the code editor when a new example is chosen. ```javascript function getDefaultExample(fileType) { const examples = { "module": `Caption = "My Application" ClientHeight = 3090 ClientWidth = 4560 Begin VB.CommandButton btnSubmit Caption = "Submit" Height = 375 Left = 1680 TabIndex = 0 Top = 2520 Width = 1215 End End Attribute VB_Name = "MainForm" Private Sub btnSubmit_Click () MsgBox "Button clicked!" End Sub`, project: `Type=Exe Form=Form1.frm Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\Windows\SysWOW64\stdole2.tlb#OLE Automation Module=Module1; Module1.bas Class=Calculator; Calculator.cls IconForm="Form1" Startup="Form1" ExeName32="MyApp.exe" Command32="" Name="Project1" HelpContextID="0" CompatibleMode="0" MajorVer=1 MinorVer=0 RevisionVer=0 AutoIncrementVer=0 ServerSupportFiles=0 VersionCompanyName="Company" CompilationType=0 OptimizationType=0 FavorPentiumPro(tm)=0 CodeViewDebugInfo=0 NoAliasing=0 BoundsCheck=0 OverflowCheck=0 FlPointCheck=0 FDIVCheck=0 UnroundedFP=0 StartMode=0 Unattended=0 Retained=0 ThreadPerObject=0 MaxNumberOfThreads=1` }; return examples[fileType] || examples.module; } ``` -------------------------------- ### VB.NET GetSetting with MsgBox Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/getsetting.html Shows how to use GetSetting to retrieve a welcome message and display it using MsgBox. This is suitable for user-facing messages or notifications. ```vbnet Sub Test() MsgBox GetSetting("MyApp", "Messages", "Welcome", "Hello!") End Sub ``` -------------------------------- ### Get Current Second from Start Time Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/second.html Retrieves the current second from a stored start time. This is useful for time-based calculations or logging. ```vb GetCurrentSecond = Second(m_startTime) ``` -------------------------------- ### Binary File Progress Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/file/loc.html Shows how to track progress while reading a Binary file, printing the percentage completion at intervals. ```vb Dim fileNum As Integer Dim data As Byte Dim fileSize As Long fileNum = FreeFile Open "data.bin" For Binary As #fileNum fileSize = LOF(fileNum) Do While Loc(fileNum) < fileSize Get #fileNum, , data ' Update progress If Loc(fileNum) Mod 1024 = 0 Then Debug.Print "Progress: " & (Loc(fileNum) / fileSize) * 100 & "%" End If Loop Close #fileNum ``` -------------------------------- ### VB6 Get Statement Syntax Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/get.html Illustrates various ways to use the Get statement in VB6, including omitting the record number. ```vb Get #1, , myRecord ``` ```vb Get #1, recordNumber, customerData ``` ```vb Get fileNum, , buffer ``` -------------------------------- ### VB6 Get Character from ASCII Code Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/chr_dollar.html Use Chr$ to get a character corresponding to a given ASCII code. For example, Chr$(65) returns 'A'. ```vb ' Example 1: Get character from code Dim ch As String ch = Chr$(65) ' Returns "A" ``` -------------------------------- ### GetSetting in a For Loop Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/getsetting.html This example demonstrates using GetSetting within a For loop to retrieve multiple settings. It iterates from 1 to 10, fetching a 'File' setting for each iteration from 'MyApp' and 'Recent'. ```vb.net Sub Test() Dim i As Integer For i = 1 To 10 files(i) = GetSetting("MyApp", "Recent", "File" & i, "") Next i End Sub ``` -------------------------------- ### VB6 Performance Counter Start Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/timer.html Starts a performance timer by recording the current time. This is typically used in conjunction with a function to get elapsed time. ```vb6 Sub StartTimer() Static timerStart As Single timerStart = Timer End Sub ``` -------------------------------- ### Get File Size using LOF Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/lof.html Example of how to get the size of an open file using the LOF function. Assumes file number 1 is open. ```vb fileSize = LOF(1) ``` -------------------------------- ### Example: Creating and Asserting an RGB Color Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/language/color.html Demonstrates how to create an RGB color using the `rgb` function and assert its properties. Ensure the `std::matches` and `vb6parse::language::Color` are imported. ```rust use std::matches; use vb6parse::language::Color; let color = Color::rgb(0xFF, 0x33, 0x12); assert!(matches!(color, Color::RGB { .. } )); assert_eq!(color, Color::RGB { red: 0xFF, green: 0x33, blue: 0x12 }); ``` -------------------------------- ### Install Rust Toolchain Source: https://github.com/scriptandcompile/vb6parse/blob/master/CONTRIBUTING.md Install the Rust toolchain using the provided script. This is a prerequisite for development. ```bash rustup-init.sh ``` -------------------------------- ### Get File Size Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/lof.html Demonstrates how to get the size of a binary file using the LOF function. Opens the file, retrieves its size, displays it, and then closes the file. ```vb Dim fileNum As Integer Dim fileSize As Long fileNum = FreeFile Open "data.bin" For Binary As #fileNum fileSize = LOF(fileNum) MsgBox "File size: " & fileSize & " bytes" Close #fileNum ``` -------------------------------- ### VB6 Width with Multiple Files Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/width.html Illustrates setting different line widths for multiple files opened concurrently. ```vb Open "narrow.txt" For Output As #1 Open "wide.txt" For Output As #2 Width #1, 40 Width #2, 120 ``` -------------------------------- ### Get Quarter Start and End using DateSerial Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/datetime/dateserial.html Functions to determine the start and end dates of a fiscal quarter using DateSerial, based on year and quarter number. ```vb Function GetQuarterStart(year As Integer, quarter As Integer) As Date Dim month As Integer month = (quarter - 1) * 3 + 1 GetQuarterStart = DateSerial(year, month, 1) End Function Function GetQuarterEnd(year As Integer, quarter As Integer) As Date Dim month As Integer month = quarter * 3 GetQuarterEnd = DateSerial(year, month + 1, 0) End Function ``` -------------------------------- ### Trim$, LTrim$, RTrim$ Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/string/trim_dollar.html Demonstrates the difference between Trim$, LTrim$, and RTrim$ in removing spaces from the beginning and end of a string. ```VB.NET Dim text As String text = " Hello " Debug.Print Trim$(text) ' "Hello" (both sides trimmed) Debug.Print LTrim$(text) ' "Hello " (left side only) Debug.Print RTrim$(text) ' " Hello" (right side only) ``` -------------------------------- ### VB6 Seek Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/seek.html Demonstrates using the Seek function to get the current file position. This snippet parses a VB6 code example and asserts its structure. ```vb6 Sub Test() Dim msg As String msg = "Current position: " & Seek(1) End Sub ``` -------------------------------- ### VB6 RightB GUID Extraction Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/rightb.html Shows how to use RightB to extract the last 8 bytes from a string, which is assumed to be a GUID. This is useful for parsing specific data formats. ```vbscript Sub ExtractGUID(guidData As String) data4 = RightB(guidData, 8) End Sub ``` -------------------------------- ### VB6 Project Wizard Input Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/interaction/inputbox.html Demonstrates using InputBox to gather project details like name, location, and description in a multi-step wizard. It checks for empty input and provides default values. ```vb6 ' Step 3 prompt = "Step 3 of 3:" & vbCrLf & _ "Enter description:" step3 = InputBox(prompt, "Project Wizard") If step3 = "" Then step3 = "(No description)" ' Create project MsgBox "Creating project:" & vbCrLf & _ "Name: " & step1 & vbCrLf & _ "Location: " & step2 & vbCrLf & _ "Description: " & step3 RunWizard = True End Function ``` -------------------------------- ### Example: Iterating Over Control Menus Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/language/controls/mod.html Shows how to create a Form control with a menu and then use the `menus` method to iterate over its menu items. ```Rust use vb6parse::*; use vb6parse::language::{Control, ControlKind, MenuControl, MenuProperties}; let control = Control::new( "MyForm".to_string(), "".to_string(), 0, ControlKind::Form { properties: Default::default(), controls: vec![], menus: vec![ MenuControl::new( "File".to_string(), "".to_string(), 0, MenuProperties { caption: "File".to_string(), ..Default::default() }, vec![], ), ], }, ); // Example usage of menus iterator would follow here, similar to children example. ``` -------------------------------- ### VB6 Second Function - Get Current Second Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/second.html Example demonstrating how to get the current second of the minute using the Second function with the Now keyword. Returns a value between 0 and 59. ```vb Dim currentSecond As Integer currentSecond = Second(Now) ' Returns 0-59 ``` -------------------------------- ### Rust TokenStream Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/lexer/token_stream.html Demonstrates creating a TokenStream, accessing the current token, advancing the stream, and backtracking. ```rust use vb6parse::language::Token; use vb6parse::lexer::TokenStream; let tokens = vec![("Dim", Token::DimKeyword), (" ", Token::Whitespace), ("x", Token::Identifier)]; let mut stream = TokenStream::new("test.bas".to_string(), tokens); assert_eq!(stream.current(), Some(&("Dim", Token::DimKeyword))); stream.advance(); assert_eq!(stream.current(), Some(&(" ", Token::Whitespace))); stream.backtrack(); assert_eq!(stream.current(), Some(&("Dim", Token::DimKeyword))); ``` -------------------------------- ### Get Full Month Name in VB.NET Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/monthname.html Use MonthName with a month number to get the full name of the month. For example, MonthName(3) returns "March". ```vb ' Example 1: Get full month name Dim monthName As String monthName = MonthName(3) ' Returns "March" ``` -------------------------------- ### VB6 Function to Get Quarter Start Date Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/month.html Calculates the start date of a fiscal quarter based on a given calendar date. It relies on helper functions GetFiscalYear and GetFiscalQuarter. ```vb Public Function GetQuarterStartDate(calendarDate As Date) As Date Dim fiscalYear As Integer Dim quarter As Integer Dim quarterStartMonth As Integer fiscalYear = GetFiscalYear(calendarDate) quarter = GetFiscalQuarter(calendarDate) quarterStartMonth = m_fiscalStartMonth + ((quarter - 1) * 3) If quarterStartMonth > 12 Then quarterStartMonth = quarterStartMonth - 12 fiscalYear = fiscalYear + 1 End If GetQuarterStartDate = DateSerial(fiscalYear, quarterStartMonth, 1) End Function ``` -------------------------------- ### VB6 Dynamic Width Setting Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/width.html Demonstrates setting the line width using a variable, allowing for dynamic control. ```vb Dim lineWidth As Integer lineWidth = 80 Open "report.txt" For Output As #1 Width #1, lineWidth ``` -------------------------------- ### Get Start of Line from Offset Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/io/source_stream.html Calculates and returns the starting offset of the line that contains the given offset. It searches backward for a newline character. If none is found, it returns 0. ```rust pub fn start_of_line_from(&self, offset: usize) -> usize { // Find the last newline character before the current offset if let Some(pos) = self.contents[..offset].rfind('\n') { pos + 1 // Return the position after the newline character } else { 0 // If no newline found, return the start of the stream } } ``` -------------------------------- ### GetSetting in a Do While Loop Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/getsetting.html This example shows how GetSetting can be used in a Do While loop to control execution based on a registry setting. The loop continues as long as the 'Running' status for 'MyApp' is 'True'. ```vb.net Sub Test() Do While GetSetting("MyApp", "Status", "Running", "True") = "True" DoWork Loop End Sub ``` -------------------------------- ### Usage Example for FormatDateRange Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/formatdatetime.html Demonstrates calling the FormatDateRange function with start and end dates. ```vb Debug.Print FormatDateRange(#1/1/2025#, #1/31/2025#) ' 1/1/2025 - 1/31/2025 ``` -------------------------------- ### VB.NET GoSub and Return Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/statements/control_flow/jump.html Demonstrates the usage of GoSub to call a subroutine and Return to exit it. The code is parsed into a CST and snapshotted for verification. ```vb.net Sub Test() GoSub Check Exit Sub Check: If x = 0 Then Return End If x = x + 1 Return End Sub ``` -------------------------------- ### VB6 MkDir Statement Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/filesystem/mkdir.html Demonstrates various ways to use the MkDir statement, including creating directories in the current directory, with full paths, on different drives, nested directories, and on network drives. ```vb ' Create a directory in the current directory MkDir "MyNewFolder" ``` ```vb ' Create a directory with full path MkDir "C:\Program Files\MyApp" ``` ```vb ' Create a directory on another drive MkDir "D:\Data\Reports" ``` ```vb ' Create nested directories (parent must exist first) MkDir "C:\Temp" MkDir "C:\Temp\Logs" MkDir "C:\Temp\Logs\Archive" ``` ```vb ' Create directory on network drive MkDir "\\Server\Share\NewFolder" ``` -------------------------------- ### Get Current Fiscal Year Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/datetime/dateserial.html Determines the current fiscal year based on the current date and the specified fiscal start month. It compares the current month to the fiscal start month. ```vb6 Function GetCurrentFiscalYear(fiscalStartMonth As Integer) As Integer Dim currentMonth As Integer currentMonth = Month(Date) If currentMonth >= fiscalStartMonth Then GetCurrentFiscalYear = Year(Date) Else GetCurrentFiscalYear = Year(Date) - 1 End If End Function ``` -------------------------------- ### VB6 GetLogPath Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/curdir_dollar.html Demonstrates how to construct a log file path using the current directory and a formatted timestamp. ```vb6 GetLogPath = CurDir$() & "\app.log" ``` -------------------------------- ### Parsing Multiple VB6 GET Statements Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/get.html Parses a VB6 subroutine containing multiple GET statements. This example verifies the parser's ability to handle sequential file read operations. ```rust #\[test\] fn multiple_get_statements() { let source = r"Sub Test() Get #1, , record1 Get #1, , record2 End Sub "; let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack(); let cst = cst_opt.expect("CST should be parsed"); let tree = cst.to_serializable(); let mut settings = insta::Settings::clone_current(); settings.set_snapshot_path("../../../../snapshots/syntax/library/statements/get"); settings.set_prepend_module_to_snapshot(false); let _guard = settings.bind_to_scope(); insta::assert_yaml_snapshot!(tree); } ``` -------------------------------- ### Example: Parsing and Serializing VB6 Code Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/parsers/cst/mod.html Demonstrates how to parse VB6 source code into a CST and then convert it to a serializable format for snapshot testing. Includes error handling for parsing failures. ```rust use vb6parse::ConcreteSyntaxTree; let source = "Sub Test()\nEnd Sub\n"; let result = ConcreteSyntaxTree::from_text("test.bas", source); let (cst_opt, failures) = result.unpack(); let cst = cst_opt.expect("Failed to parse source"); if !failures.is_empty() { for failure in failures.iter() { failure.print(); } panic!("Failed to parse source with {} errors.", failures.len()); }; let serializable = cst.to_serializable(); // Can now be used with insta::assert_yaml_snapshot! ``` -------------------------------- ### VB6 Command$() Example: Get Command Line Arguments Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/interaction/command_dollar.html A basic example demonstrating how to retrieve and store command-line arguments using the Command$() function in a Visual Basic 6 Main subroutine. ```vb Sub Main() Dim cmdLine As String cmdLine = Command$() ' Use cmdLine here End Sub ``` -------------------------------- ### Get Abbreviated Month Name in VB.NET Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/monthname.html Use MonthName with the second argument set to True to get the abbreviated name of the month. For example, MonthName(11, True) returns "Nov". ```vb ' Example 2: Get abbreviated month name Dim shortMonth As String shortMonth = MonthName(11, True) ' Returns "Nov" ``` -------------------------------- ### VB6 GetSetting Basic Usage Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/getsetting.html Demonstrates how to use the GetSetting function to retrieve a user's name from the registry, providing a default value if the setting is not found. ```vb ' Example 1: Get a simple setting with default Dim userName As String userName = GetSetting("MyApp", "User", "Name", "Guest") ``` -------------------------------- ### VB6 FileProgressMonitor Get Bytes Processed Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/seek.html Calculates the number of bytes processed since monitoring started. ```vb Public Function GetBytesProcessed() As Long GetBytesProcessed = Seek(m_FileNum) - m_StartPosition End Function ``` -------------------------------- ### Retrieve All Settings for a Section Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/environment/getallsettings.html This example demonstrates how to retrieve all settings for a given application and section, then iterate through them to print the key-value pairs. It includes a check for empty settings. ```vbscript Dim allSettings As Variant Dim i As Long allSettings = GetAllSettings("MyApp", "Preferences") If IsEmpty(allSettings) Then Debug.Print "No settings found" Else For i = LBound(allSettings, 1) To UBound(allSettings, 1) Debug.Print allSettings(i, 0) & " = " & allSettings(i, 1) Next i End If ``` -------------------------------- ### VB.NET CurDir$ Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/curdir_dollar.html Demonstrates the basic usage of the CurDir$ function to get the current directory. ```vbnet d = CurDir$("D") ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/wasm/README.md Ensures that all documentation examples within the VB6Parse project are valid and executable. ```bash # Run documentation tests cargo test --doc ``` -------------------------------- ### Get PATH Environment Variable Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/environ_dollar.html Retrieves the value of the PATH environment variable. This is a basic usage example. ```vb6 Sub Main() path = Environ$("PATH") End Sub ``` -------------------------------- ### CreateObject FileSystemObject Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/objects/createobject.html Shows how to create a FileSystemObject instance using CreateObject. ```vb6 Set fso = CreateObject("Scripting.FileSystemObject") ``` -------------------------------- ### Extracting Minute with DatePart Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/datepart.html Provides an example of using DatePart with the 'n' interval to get the minute from a timestamp. ```vb6 minute = DatePart("n", timestamp) ``` -------------------------------- ### VB6 Seek Function Basic Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/file/seek.html A basic example demonstrating how to get the current position in a binary file using the Seek function in VB6. Ensure the file is opened before calling Seek and closed afterward. ```vb ' Example 1: Get current position in binary file Dim FileNum As Integer Dim CurrentPos As Long ``` -------------------------------- ### VB6 Space Function - Basic Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/space.html Demonstrates how to create a string of a specified number of spaces using the Space function. ```vb ' Example 1: Create a string of 5 spaces Dim spaces As String spaces = Space(5) ' Returns " " (5 spaces) ``` -------------------------------- ### VB.NET AscB Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/ascb.html Demonstrates the basic usage of the AscB function to get the byte value of a character. ```vb byte2 = AscB(char2) ``` -------------------------------- ### Deployment Check Usage Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/environment/getautoserversettings.html An example of how to use the VerifyDeployment function in a deployment script to check the status of production servers. ```VB.NET Sub DeploymentCheck() Dim productionServers As Variant productionServers = Array("WEB-01", "WEB-02", "APP-01", "APP-02") If VerifyDeployment("MyApp.BusinessLogic", _ "{AAAABBBB-CCCC-DDDD-EEEE-FFFF00001111}", _ productionServers) Then MsgBox "Deployment successful on all servers" Else MsgBox "Deployment incomplete - check logs" End If End Sub ``` -------------------------------- ### Get the end of the week (Sunday) Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/weekday.html Calculates the date of the Sunday for any given date. Assumes the week starts on Monday. ```vb6 Function GetWeekEnd(anyDate As Date) As Date Dim dayNum As Integer dayNum = Weekday(anyDate, vbMonday) GetWeekEnd = anyDate + (7 - dayNum) End Function ``` -------------------------------- ### Example: Get User Name Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/environ_dollar.html Retrieves the current user's name. The USERNAME environment variable should be set. ```vb6 Dim userName As String userName = Environ$("USERNAME") ``` -------------------------------- ### VB6 Basic Width Setting Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/width.html Demonstrates setting a specific line width (80 characters) for a file opened for output. ```vb Open "output.txt" For Output As #1 Width #1, 80 Print #1, "This output will wrap at 80 characters" Close #1 ``` -------------------------------- ### Example: Get Temporary Directory Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/environ_dollar.html Retrieves the path to the temporary directory. The TEMP environment variable must be defined. ```vb6 Dim tempDir As String tempDir = Environ$("TEMP") ``` -------------------------------- ### Handle Start Mode Property Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/project/mod.html Placeholder function for handling the 'Start Mode' property. Currently empty, indicating future implementation. ```rust fn handle_start_mode<'a>( project: &mut ProjectFile<'a>, input: &mut SourceStream<'a>, property_name: &'a str, failures: &mut Vec>>, ) { // Implementation pending } ``` -------------------------------- ### VB6 Error Function Usage Examples Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/error.html Illustrates how to use the Error function in VB6 to get error messages. The first example retrieves the message for the most recent run-time error, while the second retrieves the message for a specific error number. ```vb Debug.Print Error() ' Example: "Application-defined or object-defined error" Debug.Print Error(53) ' Example: "File not found" ``` -------------------------------- ### VB6 Seek to Beginning of File Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/statements/file_operations/seek.html Demonstrates how to open a binary file and use the Seek statement to position the file pointer at the very beginning (first byte). ```vb Open "DATA.TXT" For Binary As #1 Seek #1, 1 ' Position at first byte ' Read or write operations Close #1 ``` -------------------------------- ### GetSetting as Function Argument Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/getsetting.html Demonstrates using GetSetting to provide a default configuration file path as an argument to a ProcessConfig function. ```vbscript Sub Test() ProcessConfig GetSetting("MyApp", "Config", "File", "default.cfg") End Sub ``` -------------------------------- ### VB.NET: Get Current Fiscal Year using DateSerial Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/dateserial.html Determines the current fiscal year based on the current date and the defined fiscal start month. It adjusts the year if the current month precedes the fiscal start month. ```vb Function GetCurrentFiscalYear(fiscalStartMonth As Integer) As Integer Dim currentMonth As Integer currentMonth = Month(Date) If currentMonth >= fiscalStartMonth Then GetCurrentFiscalYear = Year(Date) Else GetCurrentFiscalYear = Year(Date) - 1 End If End Function ``` -------------------------------- ### Example 4: Getting Date Components Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/string/left_dollar.html Demonstrates extracting the year from a date string using the first 4 characters. ```vb6 Dim dateStr As String dateStr = "2024-01-15" year = Left$(dateStr, 4) ' "2024" ``` -------------------------------- ### Example Usage of get_option Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/common/properties.html Demonstrates how to use the `get_option` method to retrieve a string value from properties, including handling cases where the key exists and where it is missing, showing the use of a default value. ```rust use vb6parse::files::common::Properties; let mut props = Properties::new(); props.insert("SomeKey", "SomeValue"); let value: Option = props.get_option("SomeKey", Some("DefaultValue".to_string())); assert_eq!(value, Some("SomeValue".to_string())); let default_value: Option = props.get_option("MissingKey", Some("DefaultValue".to_string())); assert_eq!(default_value, Some("DefaultValue".to_string())); // default used ``` -------------------------------- ### VB.NET Sgn Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/math/sgn.html Demonstrates the basic usage of the Sgn function in VB.NET to get the sign of an input value. ```vbnet signValue = Sgn(input) ``` -------------------------------- ### VB6 Project File Parsing Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/project/mod.html Demonstrates parsing a VB6 project file with various properties, including type, references, and custom third-party sections. This example showcases the dispatch-based property handler system. ```rust use vb6parse::*; use vb6parse::files::project::properties::CompileTargetType; let input = r#"Type=Exe Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\Windows\System32\stdole2.tlb#OLE Automation "#; let project_source_file = match SourceFile::decode_with_replacement("project1.vbp", input.as_bytes()) { Ok(source_file) => source_file, Err(e) => { e.print(); panic!("failed to decode project source code."); } }; let result = ProjectFile::parse(&project_source_file); let (project_opt, failures) = result.unpack(); if !failures.is_empty() { for failure in failures.iter() { failure.print(); } } let project = project_opt.expect("Expected project to be parsed successfully."); assert_eq!(project.project_type, CompileTargetType::Exe); let other_props = project.other_properties(); assert_eq!(other_props.len(), 1); assert!(other_props.contains_key("ThirdPartySection")); let third_party_props = other_props.get("ThirdPartySection").unwrap(); assert_eq!(third_party_props.len(), 1); assert_eq!(third_party_props.get("CustomProperty1").unwrap(), &"Value1"); ``` -------------------------------- ### VB6 Partition Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/graphics/partition.html This snippet shows a basic usage of the Partition function to get a median age range. ```vb GetMedianAgeRange = Partition(medianAge, 0, 120, m_ageGroupSize) ``` -------------------------------- ### VB6 On...GoSub Statement Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/statements/control_flow/on_statements.html Demonstrates how to use the On...GoSub statement to branch to different subroutines based on a menu choice. Each subroutine must end with a Return statement. ```vb Sub Test() Dim menuChoice As Integer menuChoice = 1 On menuChoice GoSub Menu1, Menu2, Menu3 Exit Sub Menu1: MsgBox "Menu 1 selected" Return Menu2: MsgBox "Menu 2 selected" Return Menu3: MsgBox "Menu 3 selected" Return End Sub ``` -------------------------------- ### VB6 Year Function Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/year.html This snippet demonstrates the basic usage of the Year function in VB6 to get the current year. ```vb6 Sub Test() currentYear = Year(Date) End Sub ``` -------------------------------- ### Get the start of the week (Monday) Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/datetime/weekday.html Calculates the date of the Monday for any given date. Uses vbMonday as the first day of the week. ```vb6 Function GetWeekStart(anyDate As Date) As Date Dim dayNum As Integer dayNum = Weekday(anyDate, vbMonday) GetWeekStart = anyDate - (dayNum - 1) End Function ``` -------------------------------- ### Basic Command() Usage Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/interaction/command.html Demonstrates the basic instantiation of the Command() function in VB6. This is useful for capturing the initial command-line arguments passed to the application. ```vb6 args = Command() ``` -------------------------------- ### Logging Startup Arguments in VB6 Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/library/functions/interaction/command_dollar.html This snippet logs the current date and time along with all command-line arguments to a file named 'startup.log' in the application's path. This is useful for debugging startup issues. ```vb6 Sub Main() Dim args As String Dim logFile As Integer args = Command$() logFile = FreeFile Open App.Path & "\startup.log" For Append As #logFile Print #logFile, Now & " - Started with args: " & args Close #logFile End Sub ``` -------------------------------- ### VB6 Array Slice Function Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/arrays/ubound.html Extracts a portion of an array from a start index to an end index. Use this to get a sub-array. ```vb6 Public Function ArraySlice(arr() As Variant, startIndex As Long, _ endIndex As Long) As Variant() Dim result() As Variant Dim i As Long Dim idx As Long ReDim result(0 To endIndex - startIndex) idx = 0 For i = startIndex To endIndex result(idx) = arr(i) idx = idx + 1 Next i ArraySlice = result End Function ``` -------------------------------- ### Properties Insertion and Retrieval Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/files/common/properties.html Demonstrates how to create a new Properties collection, insert a key-value pair, and retrieve an integer value using a default if the key is not found. ```rust use vb6parse::files::common::Properties; let mut props = Properties::new(); props.insert("ClientWidth", "800"); let width = props.get_i32("ClientWidth", 600); assert_eq!(width, 800); ``` -------------------------------- ### Creating an Excel Application Object Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/objects/createobject.html Example of using CreateObject to instantiate Microsoft Excel. This requires Excel to be installed and registered on the system. ```vb Set objExcel = CreateObject("Excel.Application") ``` -------------------------------- ### VB6 Create and Run Batch File Example Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/interaction/shell.html This snippet demonstrates how to create a temporary batch file, write commands to it, and then execute it using the Shell function. It includes basic error handling for file operations and process execution. ```vb Function CreateAndRunBatch(commands() As String, visible As Boolean) As Boolean On Error GoTo ErrorHandler ' Create temp batch file batchPath = Environ("TEMP") & "\temp\_" & Format(Now, "yyyymmddhhnnss") & ".bat" ' Write commands fileNum = FreeFile Open batchPath For Output As #fileNum Print #fileNum, "@echo off" For i = LBound(commands) To UBound(commands) Print #fileNum, commands(i) Next i Close #fileNum ' Execute taskId = Shell(batchPath, IIf(visible, vbNormalFocus, vbHide)) CreateAndRunBatch = (taskId <> 0) Exit Function ErrorHandler: If fileNum > 0 Then Close #fileNum CreateAndRunBatch = False End Function ``` -------------------------------- ### Example: Get Application Data Path Source: https://github.com/scriptandcompile/vb6parse/blob/master/docs/assets/coverage/src/syntax/library/functions/environment/environ_dollar.html Retrieves the path to the application data directory. The APPDATA environment variable must be defined. ```vb6 Dim appDataPath As String appDataPath = Environ$("APPDATA") If appDataPath <> "" Then ```