Compiler/Simple file inclusion pre processor: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(47 intermediate revisions by 6 users not shown)
Line 2:
 
;Task:
<br>
 
<b>Introduction</b>
<br><br>
Many programming languages allow file inclusion, so that for example, standard declarations or code-snippets can be stored in a separate source file and be included into the programs that require them at compile-time, without the need for cut-and-paste.
<br>
Line 9 ⟶ 11:
<br>
<br>
The purpose of this task is to demonstrate how a file inclusion pre-processor could be implemented in your language, for your language. This does not mean to imply that your language needs a file inclusion pre-processor - many languages don't have such a facility.
<br>
Other languages, on the other hand do have file inclusion, e.g.: C, COBOL, PL/1.
<br>
<br>
The distinction between compiled and interpreted languages should be irrelevent - this is a specialised text processing exercise - reading a source file and producing a modified source file that aldo contains the contents of one or more other files.
<br>
<br>
Hopefully, the solutions to this task will enable the file inclusion facilities of the languages to be compared, even for languages that don't need such facilities because they have sophisticated equivalents.
<br>
<br>
<b>The pre-processor</b>
<br><br>
Create a simple pre-processor that implements file-inclusion for your language.
<br>
The pre-processor need not implement macros, conditional compilation, etc.
<br>
The pre-processor need not check the validity of the resultant source. The pre-processor's job is purely to insert te specified files into the source at the required points. Whether the result is syntacticly valid or not is a matter for the compiler/interpreter when it is presented with the source.
<br>
The syntax accepted for your pre-processor should be as per the standard for your language, e.g. for C the pre-processor must recognise and handle "#include" directives. For PL/1, %include statements would be processed and for COBOL, COPY statements, etc.
<br>
The syntax accepted for your pre-processor should be as per the standard for your language, should your language have such a facility.
E.g. for C the pre-processor must recognise and handle "#include" directives. For PL/1, %include statements would be processed and for COBOL, COPY statements, and so on.
<br>
If your language does not have a standard facility for file-inclusion, implement that used by a popular compiler for the language.
<br>
If your language does not have a standard facility for file-inclusion, implement that used by a popular compiler/interpreter for the language.
If there is no such feature (e.g. more recent OO languages use import/using/etc. statements to include pre-compiled class definitions), either use the C style #include directive or choose something of your own invention.
<br>
If there is no such feature, either use the C style #include directive or choose something of your own invention, e.g., #include would be problematic for languages where # introduces a comment.
<br>
<br>
Line 26 ⟶ 42:
<br>
<br>
<b>Minimum requirements</b>
<br><br>
As a minimum, your pre-procdessor must be able to process a source file (read from a file or standard input, as you prefer) and generate another source file (written to a file or standard output, as you prefer). The file-inclusion directives in the source should be replaced by the contents of the specified files. Implementing nested file inclusion directives (i.e., if an included file contains another file-inclusion directive) is optional.
<br>
If possible, implement your pre-processor as a filter, i.e. read the main source file from standard input and write the pre-processed source to standard output.
<br>
Pre-processors for some languages offer additional facilities, such as macro expansion and conditional compilation. Your pre-processor need not implement such things.
<br>
NOTE to anyone who uses the pre-processors on this page:
<br>
<b>Notes</b>
They are supplied as-is, with no warranty - use at your own peril : )
* implementors: The Task is about implementing a pre-processor for your language, not just describing it's features. Just as the task [https://www.rosettacode.org/wiki/Calculating_the_value_of_e Calculating the value of e] is not about using your language's in-built exp function but showing how e could be calculated, this is about showing how file inclusion could be implemented - even if the compiler/interpreter you are using already has such a facility.
* the pre-processors on this page are supplied as-is, with no warranty - use at your own peril : )
 
 
;See Also
 
* [[include a file]]
<br>
<br>
 
=={{header|ALGOL 68}}==
Should work with any Algol 68 implementation that uses upper-stropping.
<br><br>Implements file inclusion via pragmatic comments as in ALGOL 68G.
<br><br>A pragmatic comment such as <code>PR read "somefile.incl.a68" PR</code> or <code>PR include "somefile.incl.a68" PR</code> can appear anywhere in the source and will cause the text of somefile.incl.a68 to be included at that point (Note, ALGOL 68G does not support "include" as an alternative to "read").
<br>The PR...PR will not be recognised inside comments or string literals and cannot appear inside a symbol, i.e. 1PR...PR2 is 1 followed by a pragmatic comment followed by 2.
<br>
PR can also be written as PRAGMA.
<br>
In ALGOL 68G, <code>PR read ...</code> only includes the file if it has not already been included., Thisthis implementationis doeshandled notby checkthis forimplementation this andbut soat includesmost the200 filedifferent everytimefiles itcan isbe referencedincluded.
<br>
Includes can be nested to a depth of 10.
<br><br>
<lang algol68># Algol 68 pre-processor #
When run, the pre-processor will read source from standard input and write the resultant source to standard output. If standard output is re-directed to a temporary source file, it can then be compiled/interpreted with the actual Algol 68 compiler.
<br>(NB: The source must end with a line-feed)
<syntaxhighlight lang="algol68"># Algol 68 pre-processor #
# Processes read/include pragmas in an Algol 68 upper stropping source #
# It is assumed _ is allowd in tags and bold words #
Line 61 ⟶ 90:
# the read/include must be in lower case #
# ALGOL 68G's read pragmatic comment only includes the file the first time #
# it is mentioned in a read pragmatic comment - this is not implemented by #
# here,keeping thea filelist isof the included each time files - the list is limited to 200 #
# entries #
BEGIN
 
Line 97 ⟶ 127:
# number of errors reported #
INT error count := 0;
# number of included files #
INT include count := 0;
# names of previously included files #
[ 1 : 200 ]STRING included files;
 
# sets the logical file end procedure of the specified file to a routine #
Line 233 ⟶ 267:
result
END # get string # ;
# getsreturns s unquoted a string denotation from the source without the quotes #
PROC get unquotedunquote string = ( STRING s )STRING:
BEGIN
STRING result := "";
# within a string denotation, "" denotes the " character #
WHILEINT havec stringpos delimiter:= DOLWB s + 1;
WHILE cpos < UPB WHILE nexts char;DO
CHAR ch = s[ c pos NOT at eof AND NOT have string delimiter];
DOIF ch = """" THEN
result# +:=have can embedded quote - it will be doubled #
OD; c pos +:= 1
IF NOT have string delimiter THEN
# unterminated string #
unterminated( "string" )
FI;
nextresult char+:= ch;
IFc havepos string delimiter+:= THEN1
# embedded string delimiter #
result +:= c
FI
OD;
result
END # get unquotedunquote string # ;
# gets a bold word from then source #
PROC get bold word = STRING:
Line 318 ⟶ 346:
IF have string delimiter THEN
# have a file name #
file name := get unquoted string;
pragment +:= file name + get whitespace;
file name := unquote string( file name )
FI;
# should now have the closing delimiter #
IF NOT have bold THEN
# no bold word in/at-the-nd-of the pragment #
bold word := ""
ELSE
# have a bold word - could be the delimiter #
pragment +:= ( bold word := get bold word )
Line 332 ⟶ 364:
# not a read/include pragmatic comment #
put string( pragment );
WHILEIF bold word :/= skipdelimiter to bold;THEN
# haven't NOTgot atthe eofclosing delimiter yet #
AND WHILE bold word /:= delimiterskip to bold;
DO SKIP OD; NOT at eof
IF at eof THEN AND bold word /= delimiter
#DO unterminatedSKIP commant #OD;
unterminated(IF """"at +eof delimiter + """ pragmatic comment" )THEN
FI; # unterminated comment #
put string unterminated( """" + delimiter + """" )
FI;
put string( delimiter )
FI
ELIF # check for an already included file and add the name to #
# the list if it hasn't been included before #
BOOL already included := FALSE;
FOR file pos TO include count
WHILE NOT ( already included := included files[ file pos ] = file name )
DO SKIP OD;
IF NOT already included THEN
# first time this file has been included #
# - add it to the list #
IF include count < UPB included files THEN
# room to include this file #
included files[ include count +:= 1 ] := file name
ELSE
# too many include files #
error( "Too many include files: " + file name )
FI
FI;
op = "read" AND already included
THEN
# the file is already included and the operation is "read" so #
# the pragma should be ignored #
SKIP
ELIF
# attemptcheck tothe include the file depth #
include depth >= UPB in stack
THEN
Line 392 ⟶ 449:
FI
 
END</langsyntaxhighlight>
{{out}}
Pre-processing the following program:
Line 419 ⟶ 476:
END
</pre>
 
=={{header|AWK}}==
AWK does not have file-inclusion as standard, however some implementations, particularly GNU Awk do provide file inclusion.
<br>This uses <code>@include</code> as the file inclusion directive, as in GAWK.
<br>It differs from GAWK syntax in that the include directive can appear inside or outside functions. The file name can be quoted or not. Nested includes are not supported.
<br>The source can be a named file or read from stdin. If it is read from stdin, <code>-v sec=sourceName</code> can be specified on the AWK command line to name the file. The pre-processed source is writen to stdout.
<syntaxhighlight lang="awk"># include.awk: simple file inclusion pre-processor
#
# the command line can specify:
# -v srcName=<source file path>
 
BEGIN {
srcName = srcName "";
} # BEGIN
 
{
if( $1 == "@include" )
{
# must include a file
includeFile( $0 );
}
else
{
# normal line
printf( "%s\n", $0 );
}
}
 
function includeFile( includeLine, fileName,
ioStat,
line )
{
# get the file name from the @include line
fileName = includeLine;
sub( /^ *@include */, "", fileName );
sub( / *$/, "", fileName );
sub( / *#.*$/, "", fileName );
if( fileName ~ /^"/ )
{
# quoted file name
sub( /^"/, "", fileName );
sub( /"$/, "", fileName );
gsub( /""/, "\"", fileName );
}
printf( "#line 1 %s\n", fileName );
while( ( ioStat = ( getline line < fileName ) ) > 0 )
{
# have a source line
printf( "%s\n", line );
}
if( ioStat < 0 )
{
# I/O error
printf( "@include %s # not found or I/O error\n", fileName );
}
close( fileName );
printf( "#line %d %s\n", NR, ( srcName != "" ? srcName : FILENAME ) );
 
} # includeFile</syntaxhighlight>
 
=={{header|J}}==
 
Preprocessing is a task which, if used at all, would more likely be tackled in J through monkey-patching (wrapping library definitions for names, overriding their prior definition).
 
Instead, here, we handle literal statements of the form <code>load'script references'</code> where 'load' appears at the beginning of the line (not indented) and 'script references' is a literal string, and nothing else appears on the line, and we replace any such line(s) with the content of the referenced script(s).
 
This approach is not recursive (and while it seems to offer little advantage over the native implementation of 'load', it does support 'load' inside multi-line string constants, as long as the reference(s) to the content being loaded would be supportable as a J script reference).
 
<syntaxhighlight lang="j">preproc=: {{
lines=. <;.2 LF,~CR-.~fread y
for_ndx. |.I.'load'-:"1 (4&{.@>) lines do.
line=. ndx{::lines
try. parse=. ;:line catch. continue. end.
if. 3~:#parse do. continue. end.
if. (<'load')~:{.parse do. continue. end.
if. ''''~:(1;0){::parse do. continue. end.
lines=. lines ndx}~ <;fread each getscripts_j_ ".1{::parse
end.
0!:0;lines
}}</syntaxhighlight>
 
=={{header|Julia}}==
Julia implements the <code>include</code> function, which includes a file into the current file for processing. Julia does JIT compiling, so neither the included file nor the file included into are necessarily compiled until their code is due to be run. One exception is the precompiling of modules, which allows preprocessed, precompiled code to be imported with the <code>using</code> or <code>import</code> keyword.
 
Since Julia already has an include function, adding another seems superfluous. However, one can be created for the purpose, and will be shown below. Such a Julia program could be compiled and run as the file <code>preprocess.jl</code>.
 
To use the program, run <code>julia preprocess.jl infile.jl outfile.jl</code> and include files using
the standard Julia syntax. Calls to the <code>include</code> function that contain a single argument which is a string in parentheses will be preproccessed. Other calls to <code>include</code> with different arguments will not be preprocessed by <code>preprocess.jl</code>.
 
<syntaxhighlight lang="julia"># preprocess.jl convert includes to file contenets
 
infile = length(ARGS) > 0 ? ARGS[1] : stdin
outfile = length(ARGS) > 1 ? ARGS[2] : stdout
 
function includefile(s)
try
m = match(r"(\s)include\(\"([^\"]+)\"\)(\s)", s)
return m.captures[1] * read(m.captures[2], String) * m.captures[3]
catch y
@warn y
return s
end
end
 
input = read(infile, String)
output = replace(input, r"\sinclude\(\"[^\"]+\"\)\s" => includefile)
write(outfile, output)
</syntaxhighlight>
 
=={{header|Phix}}==
Standard feature. Phix ships with a bunch of standard files in a builtins directory, most of which it knows how to "autoinclude", but some must be explicitly included ([http://phix.x10.mx/docs/html/include.htm full docs]). You can explicitly specify the builtins directory or not (obviously without it will look in the project directory first), and use the same mechanism for files you have written yourself. There is no limit to the number or depth of files than can be included. Relative directories are honoured, so if you specify a (partial) directory that is where it will look first for any sub-includes. You can also use single line "stub includes" to redirect include statements to different directories/versions. Note that namespaces are '''not''' supported by pwa/p2js. You can optionally use double quotes, but may then need to escape backslashes. Includes occur at compile time, as opposed to dynamically.
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">complex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">complex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- also valid</span>
<span style="color: #008080;">include</span> <span style="color: #008000;">"builtins\\complex.e"</span> <span style="color: #000080;font-style:italic;">-- ditto</span>
<!--</syntaxhighlight>-->
If the compiler detects that some file has already been included it does not do it again (from the same directory, two or more files of the same name ''can'' be included from different directories).
I should perhaps also state that include handling is part of normal compilation/interpretation, as opposed to a separate "preprocessing" step, and that each file is granted a new private scope, and while of course there is only one "global" scope, it will use the implicit include hierarchy to automatically resolve any clashes that might arise to the most appropriate one, aka "if it works standalone it should work exactly the same when included in as part of a larger application".
 
And so on to the task as specified: Since the task specifies it "is about implementing a pre-processor for ''your language'', not just describing it's features" and as per discussions on the talk page, and the above, a "preprocessor" for Phix would fail in so many ways it is simply not really worth attempting, and should certainly never actually be used.<br>
The following will replace include statements with file contents, but do '''not''' expect it to work or do anything useful on any existing [Phix] code. Mutually recursive includes will cause a mutually recursive infinite loop, until you run out of memory, that is without adding some kind of "already done" stack to the following.
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">preprocess</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">inlines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">outlines</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inlines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">inlines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"include "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">9</span><span style="color: #0000FF;">..</span><span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"--"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],{</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\t'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'"'</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">outlines</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">preprocess</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">outlines</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">line</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">outlines</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
As the Wren entry eloquently puts it: The above code is limited in the sense that all top-level variables of the imported module (not just the specifically "global" ones) are now visible in the outer scope. Consequently, the code will no longer compile if there are any name clashes.
 
In fact pwa/p2js contains some code (see insert_dollars() in p2js.exw) that renames selected pre-known top-level variables in the standard includes, eg base64.e `aleph` -> `$aleph` to minimise such disruption, however there is (as yet) no such mechanism for user-written include files, though it is on the to-do list.
 
=={{header|Raku}}==
A file pre-processor is very nearly pointless for Raku. Raku is nominally an interpreted language; in actuality, it does single pass, just-in-time compilation on the fly as it loads the file. For libraries and constants (or semi constant variables) there is a robust built-in library (module) include system for code that can be pre-compiled and used on demand. <code>use some-library;</code> to import any objects exported by the module.
 
That's great for code references and constants, but isn't really intended for text inclusion of external files. Since the text file can not be pre-compiled, there isn't much point to having such a system. (For code at least, there are many different templating system modules for text templates; primarily, though not exclusively used for on-the-fly generation of dynamic HTML / XML documents.) One of those could certainly be bent into doing something like what this task is asking for, but are probably both over- and under-powered for the job.
 
# they are mostly intended for text, not code.
# they tend to be more geared toward inserting the content of a variable rather than the content of a file, although that could be subverted pretty easily.
 
So in Raku, there isn't a readily available system to do this, there isn't much point, and it's probably a bad idea...
 
 
Ah well, that never stopped us before.
 
 
A Raku script to do source filtering / preprocessing: save it and call it 'include'
<syntaxhighlight lang="raku" line>unit sub MAIN ($file-name);
my $file = slurp $file-name;
put $file.=subst(/[^^|['{{' \s*]] '#include' \s+ (\S+) \s* '}}'?/, {run(«$*EXECUTABLE-NAME $*PROGRAM-NAME $0», :out).out.slurp(:close).trim}, :g);</syntaxhighlight>
 
This will find: any line starting with '#include' followed by a (absolute or relative) path to a file, or #include ./path/to/file.name enclosed in double curly brackets anywhere in the file.
 
It will replace the #include notation by the contents of the file referenced, will follow nested #includes arbitrarily deeply, and echo the processed file to STDOUT.
 
Let's test it out. Here is a test script and a bunch of include files.
 
Top level named... whatever, let's call it 'preprocess.raku'
<syntaxhighlight lang="raku" line># Top level test script file for #include Rosettacode
# 'Compiler/Simple file inclusion pre processor' task
 
# some code
 
say .³ for ^10;
 
#include ./include1.file
</syntaxhighlight>
 
include1.file
<pre># included #include1 file >1>
# test to ensure it only tries to execute #include of the right format
 
# more code
say .³³ for ^10;
# and more comments
 
#include ./include2.file # comments ok at end of include line
# <1<</pre>
 
include2.file
<pre># nested #include2.file >2>
say "Test for an nested include inside a line: {{ #include ./include3.file }}";
# pointless but why not? <2<</pre>
 
include3.file
<pre>>3> Yep, it works! <3<
</pre>
 
Invoke at a command line:
 
<code>raku include preprocess.raku</code>
{{out}}
<pre># Top level test script file for #include Rosettacode
# 'Compiler/Simple file inclusion pre processor' task
 
# some code
 
say .³ for ^10;
 
# included #include1 file >1>
# test to ensure it only tries to execute #include of the right format
 
# more code
say .³³ for ^10;
# and more comments
 
# nested #include2.file >2>
say "Test for an nested include inside a line: >3> Yep, it works! <3<";
# pointless but why not? <2<# comments ok at end of include line
# <1<
</pre>
 
You can either redirect that into a file, or just pass it back into the compiler to execute it:
 
<code>raku include preprocess.raku | raku</code>
{{out}}
<pre>0
1
8
27
64
125
216
343
512
729
0
1
8589934592
5559060566555523
73786976294838206464
116415321826934814453125
47751966659678405306351616
7730993719707444524137094407
633825300114114700748351602688
30903154382632612361920641803529
Test for an nested include inside a line: >3> Yep, it works! <3<</pre>
 
Note that this is not very robust, (it's 3 lines of code, what do you expect?) but it satisfies the task requirements as far as I can tell.
 
=={{header|Wren}}==
 
Wren already implements file inclusion via its '''import''' statement which can appear anywhere that a variable declaration can, including within a block, and can therefore be subject to a condition.
 
Any number of files can be imported in this way and can contain any Wren source code including other '''import''' statements to any level of nesting. However, Wren's virtual machine (VM) keeps track of the imported files and will only load a particular file once.
 
All the modules listed on the language's main page need to be imported in this way.
 
Although Wren is an interpreted language, source code is not interpreted directly. Instead a single pass compiler first converts the source code into a simple stack-based byte-code which is then interpreted by the VM.
 
However, there is no facility for outputting the byte-code to a separate file which can then be examined or manipulated prior to subsequent interpretation. Compilation and interpretation are both done as a single indivisible operation.
 
It will therefore be seen that Wren neither has nor needs a pre-processor; it doesn't support macros or other text substitution devices and imports are always in source code rather than binary form.
 
Nevertheless, it is possible to write a limited pre-processor in Wren (the VM itself is written in C):
<syntaxhighlight lang="wren">import "io" for File
 
var source = File.read("source.wren")
 
var ix
var start = 0
while ((ix = source.indexOf("import", start)) && ix >= 0) {
var ix2 = source.indexOf("\n", ix + 6)
if (ix2 == -1) ix2 = source.count
start = ix + 1
var imp = source[ix...ix2]
var tokens = imp.split(" ").where { |s| s != "" }.toList
var filePath = tokens[1][1...-1]
if (filePath.startsWith("./")) {
filePath = filePath[2..-1]
} else if (filePath.startsWith("/")) {
filePath = filePath[1..-1]
} else {
continue // leave resolution of other modules to compiler
}
var text = File.read(filePath + ".wren")
source = source[0...ix] + "\n%(text)\n" + source[ix2..-1]
}
 
File.create("source2.wren") { |file| file.writeBytes(source) }</syntaxhighlight>
<br>
The above code is limited in the sense that '''all''' top-level variables of the imported module (not just the specifically imported ones) are now visible in the outer scope. Consequently, the code will no longer compile if there are any name clashes.
 
The obvious solution of placing the imported code in a block and then 'lifting' the specifically imported variables into the outer scope does not work because of Wren's rather strange scoping rules. If you did this, then the imported module's top level variables would no longer be top-level relative to the code as a whole and hence would no longer be visible to classes defined within the module itself! For example, if you try to run the following script, you get the error shown:
<syntaxhighlight lang="wren">var B
 
{ // block starts here
var A = 2
class C {
static method1() {
System.print(A) // Error at 'A': Variable is used but not defined.
}
}
 
B = C
} // end of block
 
B.method()</syntaxhighlight>
 
Other problems include dealing with '''import''' statements which have been commented out (not catered for in the above pre-processor) and resolving import file paths which is not actually set in stone but depends on how Wren is being embedded. The above pre-processor code only deals with paths which are relative to the current directory.
9,476

edits