@@ -245,6 +245,52 @@ extern (C++) void genCmain(Scope* sc)
245245 rootHasMain = sc._module;
246246}
247247
248+ /**
249+ * Copies data from a FILE* into a newly-allocated buffer.
250+ *
251+ * The buffer is always null-terminated.
252+ */
253+ ubyte [] copyFile (FILE * fp)
254+ {
255+ enum bufIncrement = 4096 ;
256+ size_t pos = 0 ;
257+ size_t sz = bufIncrement;
258+
259+ ubyte * buf = cast (ubyte * ).malloc(sz + 1 ); // +1 for sentinel
260+ if (buf is null )
261+ {
262+ error(Loc(), " out of memory" );
263+ fatal();
264+ }
265+
266+ assert (sz > pos);
267+ size_t rlen;
268+ pos += rlen = fread(buf + pos, 1 , sz - pos, fp);
269+ while (! ferror(fp) && ! feof(fp))
270+ {
271+ if (pos == sz)
272+ {
273+ sz += bufIncrement;
274+ buf = cast (ubyte * ).realloc(buf, sz + 1 );
275+ if (buf is null )
276+ {
277+ error(Loc(), " out of memory" );
278+ fatal();
279+ }
280+ }
281+ assert (sz > pos);
282+ pos += rlen = fread(buf + pos, 1 , sz - pos, fp);
283+ }
284+ if (ferror(fp))
285+ {
286+ error(Loc(), " read error" );
287+ fatal();
288+ }
289+
290+ assert (pos < sz+ 1 );
291+ buf[pos] = ' \0 ' ;
292+ return buf[0 .. pos+ 1 ];
293+ }
248294
249295/**
250296 * DMD's real entry point
@@ -434,6 +480,8 @@ private int tryMain(size_t argc, const(char)** argv)
434480 }
435481 else if (strcmp(p + 1 , " shared" ) == 0 )
436482 global.params.dll = true ;
483+ else if (strcmp(p + 1 , " stdin" ) == 0 )
484+ global.params.readStdin = true ;
437485 else if (strcmp(p + 1 , " dylib" ) == 0 )
438486 {
439487 static if (TARGET_OSX )
@@ -1081,7 +1129,7 @@ Language changes listed by -transition=id:
10811129 {
10821130 fatal();
10831131 }
1084- if (files.dim == 0 )
1132+ if (files.dim == 0 && ! global.params.readStdin )
10851133 {
10861134 usage();
10871135 return EXIT_FAILURE ;
@@ -1210,6 +1258,10 @@ Language changes listed by -transition=id:
12101258 {
12111259 files.push(cast (char * )global.main_d); // a dummy name, we never actually look up this file
12121260 }
1261+ if (global.params.readStdin)
1262+ {
1263+ files.push(cast (char * )global.stdin_d); // a dummy name, we don't actually look it up
1264+ }
12131265 // Create Modules
12141266 Modules modules;
12151267 modules.reserve (files.dim);
@@ -1343,6 +1395,22 @@ Language changes listed by -transition=id:
13431395 }
13441396 }
13451397 }
1398+ if (global.params.readStdin)
1399+ {
1400+ for (size_t i = 0 ; 1 ; i++ )
1401+ {
1402+ assert (i != modules.dim);
1403+ Module m = modules[i];
1404+ if (strcmp(m.srcfile.name.str, global.stdin_d) == 0 )
1405+ {
1406+ /* Slow stdio-based read, because File.read doesn't work with
1407+ * stdin. */
1408+ auto buf = copyFile(stdin);
1409+ m.srcfile.setbuffer(buf.ptr, buf.length);
1410+ break ;
1411+ }
1412+ }
1413+ }
13461414 enum ASYNCREAD = false ;
13471415 static if (ASYNCREAD )
13481416 {
0 commit comments