package org.karaffe.compiler.util;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;

public class KaraffeSource implements CharSequence {

    private final String source;

    private KaraffeSource(String source) {
        this.source = Objects.requireNonNull(source);
    }

    private KaraffeSource(Path path) throws IOException {
        Objects.requireNonNull(path);
        List<String> strings = Files.readAllLines(path);
        this.source = strings.stream().reduce((l, r) -> l + "\n" + r).orElse("");
    }

    public static KaraffeSource fromString(String source) {
        return new KaraffeSource(source);
    }

    public static KaraffeSource fromPath(Path path) throws IOException {
        return new KaraffeSource(path);
    }

    @Override
    public int length() {
        return this.source.length();
    }

    @Override
    public char charAt(int index) {
        return this.source.charAt(index);
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return this.subSequence(start, end);
    }

    @Override
    public String toString() {
        return this.source;
    }

    public boolean hasFilePath() {
        return false;
    }

    public CharStream asCharStream() {
        return CharStreams.fromString(this.toString());
    }
}

@@ -139,16 +139,53 @@
 eption;%0A
+import java.io.UncheckedIOException;%0A
 import j
@@ -204,16 +204,16 @@
 .Files;%0A
-
 import j
@@ -335,16 +335,45 @@
 ence %7B%0A%0A
+    private final Path path;%0A
     priv
@@ -433,32 +433,58 @@
 tring source) %7B%0A
+        this.path = null;%0A
         this.sou
@@ -673,32 +673,58 @@
 AllLines(path);%0A
+        this.path = path;%0A
         this.sou
@@ -1511,24 +1511,61 @@
 rStream() %7B%0A
+        if (this.path == null) %7B%0A    
         retu
@@ -1608,16 +1608,215 @@
 ing());%0A
+        %7D else %7B%0A            try %7B%0A                return CharStreams.fromPath(path);%0A            %7D catch (IOException e) %7B%0A                throw new UncheckedIOException(e);%0A            %7D%0A        %7D%0A
     %7D%0A%7D%0A

Add path to KaraffeSource