ValidateScript and CompileScript

Check script code without running it, and report its errors and warnings.

These functions are exported by the KS module.

Result := ValidateScript(Code)
Result := CompileScript(Code)

Parameters

Code

Type: String

Either the path of a script file or the script source itself. If a file of that name exists it is checked, otherwise the value is checked as source.

On Windows, a local named-pipe path (\\.\pipe\Name) reads the source to check from the pipe.

Return Value

Type: Object

Both functions return an object with these properties:

PropertyDescription
IsValid1 if no errors were found, otherwise 0.
ErrorsAn Array of error messages, empty when IsValid is 1.
WarningsAn Array of warning messages. Always empty for ValidateScript.

A ValidateScript message is prefixed with its location where that is known: the file when Code names one, then the line and column, as in C:\Scripts\other.ks:3:7: message.

CompileScript splits the compiler's own report into lines, one line per element, so its Arrays also contain the report's heading lines, such as The following errors occurred:. When compilation fails, Errors can also contain the report's warning lines.

Which to Use

ValidateScriptCompileScript
What it checksSyntax: the script is parsed.Everything a build checks: the script is parsed, lowered and compiled in memory, so errors in inline C# and in the generated code are reported too.
Component neededThe parserThe compiler
Command-line equivalent--validate-syntax--validate

Error Handling

An Error is thrown if the component the function needs is not installed. Use IsComponentAvailable when the component is optional at run time. Errors in the checked code are reported in the returned object.

Remarks

Neither function runs the code: no hotkeys are registered and the auto-execute section does not run. CompileScript writes nothing to disk and does not restore packages, so a #Package the code names must already be available.

When daemon use is enabled, CompileScript first tries an existing compatible daemon from a matching Keysharp installation, avoiding loading the compiler into the calling process. It never starts a daemon and compiles locally if none is available. ValidateScript always uses the parser in the calling process.

A compiled script with a statically visible call to either function includes the component it needs; see Optional Scripting Components.

Examples

Compiles generated code before saving it.

#Import "Ks" { CompileScript }

Code := "MsgBox 'hello'"
Result := CompileScript(Code)
if Result.IsValid
    FileAppend Code, A_ScriptDir "\generated.ks"
else
    MsgBox "Generated code is invalid:`n" Result.Errors.Join("`n")

Checks the syntax of an existing file.

#Import "Ks" { ValidateScript }

Result := ValidateScript(A_ScriptDir "\other.ks")
MsgBox Result.IsValid ? "No syntax errors" : Result.Errors.Join("`n")

IsComponentAvailable, RunScript, Command-Line Options, How a Script Executes