From c3a5b150498479d64e5d6585cfccd795f12f2cfd Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Wed, 3 Aug 2022 13:40:00 -0400 Subject: [PATCH] Added Location struct Its purpose is to carry error reporting information with it outside of files. --- file/file.go | 21 +++++++++++++++++---- file/location.go | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 file/location.go diff --git a/file/file.go b/file/file.go index b2bd393..66834e9 100644 --- a/file/file.go +++ b/file/file.go @@ -7,10 +7,11 @@ var logger = log.New(os.Stderr, "", 0) // File represents a read only file that can print out formatted errors. type File struct { - path string - file *os.File - currentLine int - lines [][]byte + path string + file *os.File + currentLine int + currentColumn int + lines [][]byte } // Open opens the file specified by path and returns a new File struct. @@ -44,10 +45,12 @@ func (file *File) Read (bytes []byte) (amountRead int, err error) { if char == '\n' { file.lines = append(file.lines, []byte { }) file.currentLine ++ + file.currentColumn = 0 } else { file.lines[file.currentLine] = append ( file.lines[file.currentLine], bytes...) + file.currentColumn ++ } } @@ -100,3 +103,13 @@ func (file *File) Error (column, row, width int, message string) { func (file *File) Warn (column, row, width int, message string) { file.mistake(column, row, width, message, "!!!") } + +// Location returns a location struct describing the current position inside of +// the file. This can be stored and used to print errors. +func (file *File) Location () (location Location) { + return Location { + file: file, + row: file.currentLine, + column: file.currentColumn, + } +} diff --git a/file/location.go b/file/location.go new file mode 100644 index 0000000..68c48a0 --- /dev/null +++ b/file/location.go @@ -0,0 +1,19 @@ +package file + +// Location represents a specific point in a file. It is used for error +// reporting. +type Location struct { + file *File + row int + column int +} + +// Error prints an error at this location. +func (location Location) Error (width int, message string) { + location.file.Error(location.column, location.row, width, message) +} + +// Warn prints a warning at this location. +func (location Location) Warn (width int, message string) { + location.file.Warn(location.column, location.row, width, message) +}