utils

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2025 License: GPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

src/utils/enhanced_error_formatter.go

src/utils/error_printer.go

src/utils/error_suggestions.go

src/utils/example_enhanced_errors.go

Index

Constants

View Source
const (
	// Base colors
	ColorReset   = "\033[0m"
	ColorRed     = "\033[31m"
	ColorGreen   = "\033[32m"
	ColorYellow  = "\033[33m"
	ColorBlue    = "\033[34m"
	ColorMagenta = "\033[35m"
	ColorCyan    = "\033[36m"
	ColorWhite   = "\033[37m"

	// Bright colors
	ColorBrightRed     = "\033[91m"
	ColorBrightGreen   = "\033[92m"
	ColorBrightYellow  = "\033[93m"
	ColorBrightBlue    = "\033[94m"
	ColorBrightMagenta = "\033[95m"
	ColorBrightCyan    = "\033[96m"

	// Styles
	StyleBold      = "\033[1m"
	StyleDim       = "\033[2m"
	StyleItalic    = "\033[3m"
	StyleUnderline = "\033[4m"

	// Background colors
	BgRed    = "\033[41m"
	BgGreen  = "\033[42m"
	BgYellow = "\033[43m"
	BgBlue   = "\033[44m"
)

Enhanced ANSI color codes

View Source
const (
	Reset  = "\033[0m"
	Red    = "\033[31m"
	Green  = "\033[32m"
	Yellow = "\033[33m"
	Blue   = "\033[34m"
	Bold   = "\033[1m"
	Cyan   = "\033[36m"
)

ANSI color codes for terminal output

View Source
const MAX_REPL_HISTORY = 1000

Variables

View Source
var ErrorPatterns = []ErrorPattern{

	{
		Pattern: regexp.MustCompile(`identifier not found: (.+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Undefined identifier",
			Description: "The identifier you're trying to use hasn't been defined in the current scope.",
			Fixes: []object.ErrorFix{
				{
					Description: "Define the identifier before using it",
				},
				{
					Description: "Check for typos in the identifier name",
				},
				{
					Description: "Import the module containing this identifier",
				},
			},
		},
		ContextHelp: "Variables and functions must be defined before they can be used. In Carrion, use 'spell' for functions and simple assignment for variables.",
	},

	{
		Pattern: regexp.MustCompile(`type mismatch: (.+) (.+) (.+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Type mismatch",
			Description: "You're trying to perform an operation on incompatible types.",
			Fixes: []object.ErrorFix{
				{
					Description: "Use type conversion functions: int(), float(), str(), bool()",
				},
				{
					Description: "Check that both operands are of compatible types",
				},
				{
					Description: "Use appropriate operators for the data types",
				},
			},
		},
		ContextHelp: "Carrion has dynamic typing but operations must be performed on compatible types. Use conversion functions when needed.",
	},

	{
		Pattern: regexp.MustCompile(`wrong number of arguments: want=(\d+), got=(\d+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Incorrect argument count",
			Description: "The function call has the wrong number of arguments.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check the function definition and provide the correct number of arguments",
				},
				{
					Description: "Use default parameters if the function supports them",
				},
				{
					Description: "Review the function signature for required vs optional parameters",
				},
			},
		},
		ContextHelp: "Function calls must match the number of parameters defined in the function signature.",
	},

	{
		Pattern: regexp.MustCompile(`division by zero`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Division by zero",
			Description: "Division by zero is undefined and not allowed.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check if the divisor is zero before performing division",
				},
				{
					Description: "Use conditional logic: if divisor != 0:",
				},
				{
					Description: "Handle the zero case with appropriate error handling",
				},
			},
		},
		ContextHelp: "Always validate that divisors are non-zero before performing division operations.",
	},

	{
		Pattern: regexp.MustCompile(`invalid assignment target`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Invalid assignment target",
			Description: "You can only assign values to variables, not to expressions or literals.",
			Fixes: []object.ErrorFix{
				{
					Description: "Ensure the left side of '=' is a variable name",
				},
				{
					Description: "Use method calls for object property assignment",
				},
				{
					Description: "For arrays, use methods like append() or set() instead of direct indexing",
				},
			},
		},
		ContextHelp: "In Carrion, you cannot assign to expressions like function calls or array indices directly.",
	},

	{
		Pattern: regexp.MustCompile(`index out of bounds: (\d+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Index out of bounds",
			Description: "You're trying to access an array or string index that doesn't exist.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check the array/string length before accessing indices",
				},
				{
					Description: "Use len() function to get the size: if index < len(array):",
				},
				{
					Description: "Use safe access methods that return None for invalid indices",
				},
			},
		},
		ContextHelp: "Array and string indices start at 0 and go up to len(collection) - 1.",
	},

	{
		Pattern: regexp.MustCompile(`expected next token to be (.+), got (.+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Unexpected token",
			Description: "The parser expected a different token at this position.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check the syntax and add the expected token",
				},
				{
					Description: "Review language syntax rules for this construct",
				},
				{
					Description: "Look for missing punctuation or keywords",
				},
			},
		},
		ContextHelp: "Syntax errors occur when the code doesn't follow Carrion's grammar rules.",
	},

	{
		Pattern: regexp.MustCompile(`expected.*COLON`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Missing colon",
			Description: "Control structures and function definitions require a colon (:) at the end.",
			Fixes: []object.ErrorFix{
				{
					Description: "Add ':' at the end of if, for, while, spell, or grim statements",
				},
				{
					Description: "Example: if condition: or spell function_name():",
				},
			},
		},
		ContextHelp: "Colons are required after control flow keywords and function/class definitions in Carrion.",
	},

	{
		Pattern: regexp.MustCompile(`expected.*INDENT`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Missing indentation",
			Description: "Code blocks after ':' must be indented.",
			Fixes: []object.ErrorFix{
				{
					Description: "Indent the code block with 4 spaces",
				},
				{
					Description: "Ensure consistent indentation throughout the block",
				},
				{
					Description: "Use spaces, not tabs, for indentation",
				},
			},
		},
		ContextHelp: "Carrion uses indentation to define code blocks, similar to Python. Use 4 spaces per indentation level.",
	},

	{
		Pattern: regexp.MustCompile(`module (.+) not found`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Module not found",
			Description: "The module you're trying to import doesn't exist or isn't in the import path.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check the module name for typos",
				},
				{
					Description: "Ensure the module file exists in the correct location",
				},
				{
					Description: "Check that the module is in the Carrion standard library",
				},
			},
		},
		ContextHelp: "Modules must be available in the current directory or standard library path.",
	},

	{
		Pattern: regexp.MustCompile(`(.+) has no attribute (.+)`),
		Suggestion: object.ErrorSuggestion{
			Title:       "Attribute not found",
			Description: "The object doesn't have the attribute or method you're trying to access.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check the object type and available methods",
				},
				{
					Description: "Use type() to verify the object type",
				},
				{
					Description: "Check for typos in the attribute name",
				},
			},
		},
		ContextHelp: "Objects only have attributes and methods that are defined for their type.",
	},

	{
		Pattern: regexp.MustCompile(`.*None.*has no.*`),
		Suggestion: object.ErrorSuggestion{
			Title:       "None value error",
			Description: "You're trying to use None as if it were a different type.",
			Fixes: []object.ErrorFix{
				{
					Description: "Check if the value is None before using it",
				},
				{
					Description: "Use conditional logic: if value is not None:",
				},
				{
					Description: "Provide default values for potentially None results",
				},
			},
		},
		ContextHelp: "None represents the absence of a value. Always check for None before using values that might be None.",
	},
}

Common error patterns with suggestions

View Source
var LanguageSpecificSuggestions = map[string]object.ErrorSuggestion{
	"spell_syntax": {
		Title:       "Function definition syntax",
		Description: "Functions in Carrion are defined using the 'spell' keyword.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use 'spell function_name():' for function definitions",
			},
			{
				Description: "Example: spell greet(name): return f\"Hello, {name}!\"",
			},
		},
	},

	"grim_syntax": {
		Title:       "Class definition syntax",
		Description: "Classes in Carrion are defined using the 'grim' keyword.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use 'grim ClassName:' for class definitions",
			},
			{
				Description: "Example: grim Person: spell init(name): self.name = name",
			},
		},
	},

	"array_operations": {
		Title:       "Array operations",
		Description: "Carrion arrays have special methods for manipulation.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use array.append(item) to add elements",
			},
			{
				Description: "Use array[index] to access elements",
			},
			{
				Description: "Use len(array) to get array length",
			},
		},
	},

	"string_operations": {
		Title:       "String operations",
		Description: "Carrion strings support various manipulation methods.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use string.upper() and string.lower() for case conversion",
			},
			{
				Description: "Use f\"Hello {name}\" for string interpolation",
			},
			{
				Description: "Use string.find(substring) to search within strings",
			},
		},
	},

	"control_flow": {
		Title:       "Control flow",
		Description: "Carrion uses 'otherwise' instead of 'elif' and specific loop keywords.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use 'otherwise' instead of 'elif' in conditional statements",
			},
			{
				Description: "Use 'stop' instead of 'break' and 'skip' instead of 'continue'",
			},
			{
				Description: "Use 'match/case' for pattern matching",
			},
		},
	},

	"error_handling": {
		Title:       "Error handling",
		Description: "Carrion uses 'attempt/ensnare/resolve' for error handling.",
		Fixes: []object.ErrorFix{
			{
				Description: "Use 'attempt:' instead of 'try:'",
			},
			{
				Description: "Use 'ensnare ErrorType:' instead of 'except:'",
			},
			{
				Description: "Use 'resolve:' instead of 'finally:'",
			},
		},
	},
}

Language-specific suggestions for common patterns

Functions

func ClearReplHistory

func ClearReplHistory()

ClearReplHistory clears the stored REPL history

func ConvertParseErrorsToEnhanced added in v0.1.8

func ConvertParseErrorsToEnhanced(filename string, content string, errors []string) []object.EnhancedError

ConvertParseErrorsToEnhanced converts traditional parser errors to enhanced errors

func CreateContextualErrorMessage added in v0.1.8

func CreateContextualErrorMessage(originalMessage string, context map[string]string) string

CreateContextualErrorMessage creates a more helpful error message with context

func CreateSpanFromPosition added in v0.1.8

func CreateSpanFromPosition(pos object.SourcePosition) object.ErrorSpan

Helper function to create a span from a single position

func CreateSpanFromTokens added in v0.1.8

func CreateSpanFromTokens(start, end object.SourcePosition) object.ErrorSpan

Helper function to create a span from token positions

func DemonstrateErrorMigration added in v0.1.8

func DemonstrateErrorMigration()

DemonstrateErrorMigration shows how to migrate from old errors to enhanced errors

func EnhanceErrorWithSuggestions added in v0.1.8

func EnhanceErrorWithSuggestions(err *object.EnhancedError, sourceCode string) *object.EnhancedError

EnhanceErrorWithSuggestions adds contextual suggestions to an error

func ExampleEnhancedErrorSystem added in v0.1.8

func ExampleEnhancedErrorSystem()

ExampleEnhancedErrorSystem demonstrates the enhanced error system

func FormatSuggestionForDisplay added in v0.1.8

func FormatSuggestionForDisplay(suggestion object.ErrorSuggestion) string

FormatSuggestionForDisplay formats a suggestion for console output

func GetCodeSuggestions added in v0.1.8

func GetCodeSuggestions(errorType object.ErrorCategory, sourceCode string) []object.ErrorSuggestion

GetCodeSuggestions returns suggestions for improving code quality

func GetErrorDocumentation added in v0.1.8

func GetErrorDocumentation(errorCode string) string

GetErrorDocumentation returns documentation links for error types

func PrintEnhancedError added in v0.1.8

func PrintEnhancedError(err *object.EnhancedError)

PrintEnhancedError formats and prints an enhanced error with comprehensive context

func PrintEnhancedParseError added in v0.1.8

func PrintEnhancedParseError(filename string, content string, errors []object.EnhancedError)

PrintEnhancedParseError prints enhanced parser errors

func PrintError

func PrintError(err *object.ErrorWithTrace)

PrintError formats and prints a Carrion error with source context

func PrintParseFail

func PrintParseFail(filename string, content string, errors []string)

PrintParseFail formats parser error information

func RegisterReplLine

func RegisterReplLine(lineNum int, content string)

RegisterReplLine stores a line from REPL history for error context

func RunAllExamples added in v0.1.8

func RunAllExamples()

RunAllExamples runs all error system examples

func ShowErrorComparison added in v0.1.8

func ShowErrorComparison()

ShowErrorComparison compares old and new error output

Types

type ErrorPattern added in v0.1.8

type ErrorPattern struct {
	Pattern     *regexp.Regexp
	Suggestion  object.ErrorSuggestion
	ContextHelp string
}

ErrorPattern represents a pattern for matching error messages

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL