Reading the file lines as locs in Rascal

Viewed 49

In the file IO module there is a function that reads the lines from the file. list[str] fileLines = readFileLines(fileLoc);

The function neatly returns the strings. Each of these strings are also denotable as a loc with the fileLoc(O, L, <BL, BC> , <EL,EC>) format. How can I load the lines from the file as loc resources?

1 Answers

Short answer: The library function readFiles takes a source location as argument and reads the contents of the file. If that source location contains position information then it will only read the part of the file corresponding to that position information.

Somewhat longer answer:

Here is an illustration:

module Example
    
void main() { 
    str text = "a\nbc\ndef\n";
    loc tmpLoc = |home:///tmp.txt|;
    writeFile(tmpLoc, text);    // write example text to file
    
    // Read lines back and print them
    println("Using readFileLines:");
    for(s <- readFileLines(tmpLoc)) println(s);
    
    // Add position information to tmpLoc that corresponds to each of the lines,
    // read it back and print it:
    
    println("Using source location with position info:");
    println(readFile(tmpLoc[offset=0][length=1]));
    println(readFile(tmpLoc[offset=2][length=2]));
    println(readFile(tmpLoc[offset=5][length=3]));
}

the expected output is:

Using readFileLines:
a
bc
def
Using source location with position info:
a
bc
def

Final remarks:

  • Usually position information is generated automatically by tools (for example a parser); programmers mostly use that information, they don't have to create it (but they can).
  • Parsers usually generate full line and column information, here we only use offset and length.
Related