Debian Codegraph @

gcc/d/dmd/dmodule.d

raw
1 /**
2 * Defines a package and module.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/module.html, Modules)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dmodule.d, _dmodule.d)
10 * Documentation: https://dlang.org/phobos/dmd_dmodule.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dmodule.d
12 */
13
14 module dmd.dmodule;
15
16 import core.stdc.stdio;
17 import core.stdc.stdlib;
18 import core.stdc.string;
19
20 import dmd.aggregate;
21 import dmd.arraytypes;
22 import dmd.astcodegen;
23 import dmd.astenums;
24 import dmd.common.outbuffer;
25 import dmd.compiler;
26 import dmd.cparse;
27 import dmd.declaration;
28 import dmd.dimport;
29 import dmd.dmacro;
30 import dmd.doc;
31 import dmd.dscope;
32 import dmd.dsymbol;
33 import dmd.dsymbolsem : dsymbolSemantic, importAll, load, include;
34 import dmd.errors;
35 import dmd.errorsink;
36 import dmd.expression;
37 import dmd.expressionsem;
38 import dmd.file_manager;
39 import dmd.func;
40 import dmd.globals;
41 import dmd.gluelayer;
42 import dmd.id;
43 import dmd.identifier;
44 import dmd.location;
45 import dmd.parse;
46 import dmd.root.array;
47 import dmd.root.file;
48 import dmd.root.filename;
49 import dmd.root.port;
50 import dmd.root.rmem;
51 import dmd.root.string;
52 import dmd.rootobject;
53 import dmd.semantic2;
54 import dmd.semantic3;
55 import dmd.target;
56 import dmd.utils;
57 import dmd.visitor;
58
59 version (Windows)
60 {
61 enum PathSeparator = '\\';
62 }
63 else version (Posix)
64 {
65 enum PathSeparator = '/';
66 }
67 else
68 static assert(0);
69
70 version (IN_GCC) {}
71 else version (IN_LLVM) {}
72 else version = MARS;
73
74 // function used to call semantic3 on a module's dependencies
75 void semantic3OnDependencies(Module m)
76 {
77 if (!m)
78 return;
79
80 if (m.semanticRun > PASS.semantic3)
81 return;
82
83 m.semantic3(null);
84
85 foreach (i; 1 .. m.aimports.length)
86 semantic3OnDependencies(m.aimports[i]);
87 }
88
89 /**
90 * Remove generated .di files on error and exit
91 */
92 void removeHdrFilesAndFail(ref Param params, ref Modules modules) nothrow
93 {
94 if (params.dihdr.doOutput)
95 {
96 foreach (m; modules)
97 {
98 if (m.filetype == FileType.dhdr)
99 continue;
100 File.remove(m.hdrfile.toChars());
101 }
102 }
103
104 fatal();
105 }
106
107 /**
108 * Converts a chain of identifiers to the filename of the module
109 *
110 * Params:
111 * packages = the names of the "parent" packages
112 * ident = the name of the child package or module
113 *
114 * Returns:
115 * the filename of the child package or module
116 */
117 private const(char)[] getFilename(Identifier[] packages, Identifier ident) nothrow
118 {
119 const(char)[] filename = ident.toString();
120
121 OutBuffer buf;
122 OutBuffer dotmods;
123 auto modAliases = &global.params.modFileAliasStrings;
124
125 if (packages.length == 0 && modAliases.length == 0)
126 return filename;
127
128 void checkModFileAlias(const(char)[] p)
129 {
130 /* Check and replace the contents of buf[] with
131 * an alias string from global.params.modFileAliasStrings[]
132 */
133 dotmods.writestring(p);
134 foreach_reverse (const m; *modAliases)
135 {
136 const q = strchr(m, '=');
137 assert(q);
138 if (dotmods.length == q - m && memcmp(dotmods.peekChars(), m, q - m) == 0)
139 {
140 buf.setsize(0);
141 auto rhs = q[1 .. strlen(q)];
142 if (rhs.length > 0 && (rhs[$ - 1] == '/' || rhs[$ - 1] == '\\'))
143 rhs = rhs[0 .. $ - 1]; // remove trailing separator
144 buf.writestring(rhs);
145 break; // last matching entry in ms[] wins
146 }
147 }
148 dotmods.writeByte('.');
149 }
150
151 foreach (pid; packages)
152 {
153 const p = pid.toString();
154 buf.writestring(p);
155 if (modAliases.length)
156 checkModFileAlias(p);
157 buf.writeByte(PathSeparator);
158 }
159 buf.writestring(filename);
160 if (modAliases.length)
161 checkModFileAlias(filename);
162 buf.writeByte(0);
163 filename = buf.extractSlice()[0 .. $ - 1];
164
165 return filename;
166 }
167
168 /***********************************************************
169 */
170 extern (C++) class Package : ScopeDsymbol
171 {
172 PKG isPkgMod = PKG.unknown;
173 uint tag; // auto incremented tag, used to mask package tree in scopes
174 Module mod; // !=null if isPkgMod == PKG.module_
175
176 final extern (D) this(Loc loc, Identifier ident) nothrow
177 {
178 super(loc, ident);
179 __gshared uint packageTag;
180 this.tag = packageTag++;
181 this.dsym = DSYM.package_;
182 }
183
184 override const(char)* kind() const nothrow
185 {
186 return "package";
187 }
188
189 override bool equals(const RootObject o) const
190 {
191 // custom 'equals' for bug 17441. "package a" and "module a" are not equal
192 if (this == o)
193 return true;
194 auto p = cast(Package)o;
195 return p && isModule() == p.isModule() && ident.equals(p.ident);
196 }
197
198 /****************************************************
199 * Input:
200 * packages[] the pkg1.pkg2 of pkg1.pkg2.mod
201 * Returns:
202 * the symbol table that mod should be inserted into
203 * Output:
204 * *pparent the rightmost package, i.e. pkg2, or NULL if no packages
205 * *ppkg the leftmost package, i.e. pkg1, or NULL if no packages
206 */
207 extern (D) static DsymbolTable resolve(Identifier[] packages, Dsymbol* pparent, Package* ppkg)
208 {
209 DsymbolTable dst = Module.modules;
210 Dsymbol parent = null;
211 //printf("Package::resolve()\n");
212 if (ppkg)
213 *ppkg = null;
214 foreach (pid; packages)
215 {
216 Package pkg;
217 Dsymbol p = dst.lookup(pid);
218 if (!p)
219 {
220 pkg = new Package(Loc.initial, pid);
221 dst.insert(pkg);
222 pkg.parent = parent;
223 pkg.symtab = new DsymbolTable();
224 }
225 else
226 {
227 pkg = p.isPackage();
228 assert(pkg);
229 // It might already be a module, not a package, but that needs
230 // to be checked at a higher level, where a nice error message
231 // can be generated.
232 // dot net needs modules and packages with same name
233 // But we still need a symbol table for it
234 if (!pkg.symtab)
235 pkg.symtab = new DsymbolTable();
236 }
237 parent = pkg;
238 dst = pkg.symtab;
239 if (ppkg && !*ppkg)
240 *ppkg = pkg;
241 if (pkg.isModule())
242 {
243 // Return the module so that a nice error message can be generated
244 if (ppkg)
245 *ppkg = cast(Package)p;
246 break;
247 }
248 }
249
250 if (pparent)
251 *pparent = parent;
252 return dst;
253 }
254
255 /**
256 * Checks if pkg is a sub-package of this
257 *
258 * For example, if this qualifies to 'a1.a2' and pkg - to 'a1.a2.a3',
259 * this function returns 'true'. If it is other way around or qualified
260 * package paths conflict function returns 'false'.
261 *
262 * Params:
263 * pkg = possible subpackage
264 *
265 * Returns:
266 * see description
267 */
268 final bool isAncestorPackageOf(const Package pkg) const
269 {
270 if (this == pkg)
271 return true;
272 if (!pkg || !pkg.parent)
273 return false;
274 return isAncestorPackageOf(pkg.parent.isPackage());
275 }
276
277 override void accept(Visitor v)
278 {
279 v.visit(this);
280 }
281
282 final Module isPackageMod()
283 {
284 if (isPkgMod == PKG.module_)
285 {
286 return mod;
287 }
288 return null;
289 }
290
291 /**
292 * Checks for the existence of a package.d to set isPkgMod appropriately
293 * if isPkgMod == PKG.unknown
294 */
295 final void resolvePKGunknown()
296 {
297 if (isModule())
298 return;
299 if (isPkgMod != PKG.unknown)
300 return;
301
302 Identifier[] packages;
303 for (Dsymbol s = this.parent; s; s = s.parent)
304 packages ~= s.ident;
305 reverse(packages);
306
307 ImportPathInfo pathThatFoundThis;
308 if (Module.find(getFilename(packages, ident), pathThatFoundThis))
309 Module.load(Loc.initial, packages, this.ident, pathThatFoundThis);
310 else
311 isPkgMod = PKG.package_;
312 }
313 }
314
315 /***********************************************************
316 */
317 extern (C++) final class Module : Package
318 {
319 extern (C++) __gshared Module rootModule;
320 extern (C++) __gshared DsymbolTable modules; // symbol table of all modules
321 extern (C++) __gshared Modules amodules; // array of all modules
322 extern (C++) __gshared Dsymbols deferred; // deferred Dsymbol's needing semantic() run on them
323 extern (C++) __gshared Dsymbols deferred2; // deferred Dsymbol's needing semantic2() run on them
324 extern (C++) __gshared Dsymbols deferred3; // deferred Dsymbol's needing semantic3() run on them
325
326 static void _init()
327 {
328 modules = new DsymbolTable();
329 }
330
331 /**
332 * Deinitializes the global state of the compiler.
333 *
334 * This can be used to restore the state set by `_init` to its original
335 * state.
336 */
337 static void deinitialize()
338 {
339 modules = modules.init;
340 }
341
342 extern (C++) __gshared AggregateDeclaration moduleinfo;
343
344 const(char)[] arg; // original argument name
345 ModuleDeclaration* md; // if !=null, the contents of the ModuleDeclaration declaration
346 const FileName srcfile; // input source file
347 FileName objfile; // output .obj file
348 FileName hdrfile; // 'header' file
349 FileName docfile; // output documentation file
350 const(ubyte)[] src; /// Raw content of the file
351 uint errors; // if any errors in file
352 uint numlines; // number of lines in source file
353 FileType filetype; // source file type
354 bool hasAlwaysInlines; // contains references to functions that must be inlined
355 bool isPackageFile; // if it is a package.d
356 Edition edition; // language edition that this module is compiled with
357 Package pkg; // if isPackageFile is true, the Package that contains this package.d
358 Strings contentImportedFiles; // array of files whose content was imported
359 int needmoduleinfo;
360 private ThreeState selfimports;
361 private ThreeState rootimports;
362 Dsymbol[void*] tagSymTab; /// ImportC: tag symbols that conflict with other symbols used as the index
363
364 private OutBuffer defines; // collect all the #define lines here
365
366
367 /*************************************
368 * Return true if module imports itself.
369 */
370 bool selfImports()
371 {
372 //printf("Module::selfImports() %s\n", toChars());
373 if (selfimports == ThreeState.none)
374 {
375 foreach (Module m; amodules)
376 m.insearch = false;
377 selfimports = imports(this) ? ThreeState.yes : ThreeState.no;
378 foreach (Module m; amodules)
379 m.insearch = false;
380 }
381 return selfimports == ThreeState.yes;
382 }
383
384 /*************************************
385 * Return true if module imports root module.
386 */
387 bool rootImports()
388 {
389 //printf("Module::rootImports() %s\n", toChars());
390 if (rootimports == ThreeState.none)
391 {
392 foreach (Module m; amodules)
393 m.insearch = false;
394 rootimports = ThreeState.no;
395 foreach (Module m; amodules)
396 {
397 if (m.isRoot() && imports(m))
398 {
399 rootimports = ThreeState.yes;
400 break;
401 }
402 }
403 foreach (Module m; amodules)
404 m.insearch = false;
405 }
406 return rootimports == ThreeState.yes;
407 }
408
409 Identifier searchCacheIdent;
410 Dsymbol searchCacheSymbol; // cached value of search
411 SearchOptFlags searchCacheFlags; // cached flags
412 bool insearch;
413
414 /**
415 * A root module is one that will be compiled all the way to
416 * object code. This field holds the root module that caused
417 * this module to be loaded. If this module is a root module,
418 * then it will be set to `this`. This is used to determine
419 * ownership of template instantiation.
420 */
421 Module importedFrom;
422
423 Dsymbols* decldefs; // top level declarations for this Module
424
425 Modules aimports; // all imported modules
426
427 Identifiers* debugids; // debug identifiers
428 Identifiers* debugidsNot; // forward referenced debug identifiers
429
430 Identifiers* versionids; // version identifiers
431 Identifiers* versionidsNot; // forward referenced version identifiers
432
433 MacroTable macrotable; // document comment macros
434 Escape* _escapetable; // document comment escapes
435
436 size_t nameoffset; // offset of module name from start of ModuleInfo
437 size_t namelen; // length of module name in characters
438
439 extern (D) this(Loc loc, const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen)
440 {
441 super(loc, ident);
442 this.dsym = DSYM.module_;
443 const(char)[] srcfilename;
444 //printf("Module::Module(filename = '%.*s', ident = '%s')\n", cast(int)filename.length, filename.ptr, ident.toChars());
445 this.arg = filename;
446 srcfilename = FileName.defaultExt(filename, mars_ext);
447 if (target.run_noext && global.params.run &&
448 !FileName.ext(filename) &&
449 FileName.exists(srcfilename) == 0 &&
450 FileName.exists(filename) == 1)
451 {
452 FileName.free(srcfilename.ptr);
453 srcfilename = FileName.sansExt(filename);
454 }
455 else if (!FileName.equalsExt(srcfilename, mars_ext) &&
456 !FileName.equalsExt(srcfilename, hdr_ext) &&
457 !FileName.equalsExt(srcfilename, c_ext) &&
458 !FileName.equalsExt(srcfilename, i_ext) &&
459 !FileName.equalsExt(srcfilename, dd_ext))
460 {
461
462 error(loc, "%s `%s` source file name '%.*s' must have .%.*s extension",
463 kind, toPrettyChars,
464 cast(int)srcfilename.length, srcfilename.ptr,
465 cast(int)mars_ext.length, mars_ext.ptr);
466 fatal();
467 }
468
469 srcfile = FileName(srcfilename);
470 objfile = setOutfilename(global.params.objname, global.params.objdir, filename, target.obj_ext);
471 if (doDocComment)
472 setDocfile();
473 if (doHdrGen)
474 hdrfile = setOutfilename(global.params.dihdr.name, global.params.dihdr.dir, arg, hdr_ext);
475
476 this.edition = Edition.legacy;
477 }
478
479 extern (D) this(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen)
480 {
481 this(Loc.initial, filename, ident, doDocComment, doHdrGen);
482 }
483
484 static Module create(const(char)* filename, Identifier ident, int doDocComment, int doHdrGen)
485 {
486 return create(filename.toDString, ident, doDocComment, doHdrGen);
487 }
488
489 extern (D) static Module create(const(char)[] filename, Identifier ident, int doDocComment, int doHdrGen)
490 {
491 return new Module(Loc.initial, filename, ident, doDocComment, doHdrGen);
492 }
493
494 static const(char)* find(const(char)* filename)
495 {
496 ImportPathInfo pathThatFoundThis; // is this needed? In fact is this function needed still???
497 return find(filename.toDString, pathThatFoundThis).ptr;
498 }
499
500 extern (D) static const(char)[] find(const(char)[] filename, out ImportPathInfo pathThatFoundThis)
501 {
502 ptrdiff_t whichPathFoundThis;
503 const(char)[] ret = global.fileManager.lookForSourceFile(filename, global.path[], whichPathFoundThis);
504
505 if (whichPathFoundThis >= 0)
506 pathThatFoundThis = global.path[whichPathFoundThis];
507 return ret;
508 }
509
510 extern (C++) static Module load(Loc loc, Identifiers* packages, Identifier ident)
511 {
512 return load(loc, packages ? (*packages)[] : null, ident);
513 }
514
515 extern (D) static Module load(Loc loc, Identifier[] packages, Identifier ident, ImportPathInfo pathInfo = ImportPathInfo.init)
516 {
517 //printf("Module::load(ident = '%s')\n", ident.toChars());
518 // Build module filename by turning:
519 // foo.bar.baz
520 // into:
521 // foo\bar\baz
522 const(char)[] filename = getFilename(packages, ident);
523 // Look for the source file
524 ImportPathInfo importPathThatFindUs;
525 if (const result = find(filename, importPathThatFindUs))
526 {
527 filename = result; // leaks
528 pathInfo = importPathThatFindUs;
529 }
530
531 auto m = new Module(loc, filename, ident, 0, 0);
532
533 // TODO: apply import path information (pathInfo) on to module
534
535 if (!m.read(loc))
536 return null;
537 if (global.params.v.verbose)
538 {
539 OutBuffer buf;
540 foreach (pid; packages)
541 {
542 buf.writestring(pid.toString());
543 buf.writeByte('.');
544 }
545 buf.printf("%s\t(%s)", ident.toChars(), m.srcfile.toChars());
546 message("import %s", buf.peekChars());
547 }
548 if((m = m.parse()) is null) return null;
549
550 return m;
551 }
552
553 override const(char)* kind() const
554 {
555 return "module";
556 }
557
558 /*********************************************
559 * Combines things into output file name for .html and .di files.
560 * Input:
561 * name Command line name given for the file, NULL if none
562 * dir Command line directory given for the file, NULL if none
563 * arg Name of the source file
564 * ext File name extension to use if 'name' is NULL
565 * global.params.preservePaths get output path from arg
566 * srcfile Input file - output file name must not match input file
567 */
568 extern(D) FileName setOutfilename(const(char)[] name, const(char)[] dir, const(char)[] arg, const(char)[] ext)
569 {
570 const(char)[] docfilename;
571 if (name)
572 {
573 docfilename = name;
574 }
575 else
576 {
577 const(char)[] argdoc;
578 if (global.params.preservePaths)
579 argdoc = arg;
580 else
581 argdoc = FileName.name(arg);
582
583 if (global.params.fullyQualifiedObjectFiles)
584 {
585 const fqn = md ? md.toString() : toString();
586 argdoc = FileName.replaceName(argdoc, fqn);
587
588 // add ext, otherwise forceExt will make nested.module into nested.<ext>
589 const bufferLength = argdoc.length + 1 + ext.length + /* null terminator */ 1;
590 char[] s = new char[bufferLength];
591 s[0 .. argdoc.length] = argdoc[];
592 s[argdoc.length] = '.';
593 s[$-1-ext.length .. $-1] = ext[];
594 s[$-1] = 0;
595 argdoc = s;
596 }
597
598 // If argdoc doesn't have an absolute path, make it relative to dir
599 if (!FileName.absolute(argdoc))
600 {
601 //FileName::ensurePathExists(dir);
602 argdoc = FileName.combine(dir, argdoc);
603 }
604 docfilename = FileName.forceExt(argdoc, ext);
605 }
606 if (FileName.equals(docfilename, srcfile.toString()))
607 {
608 error(loc, "%s `%s` source file and output file have same name '%s'",
609 kind, toPrettyChars, srcfile.toChars());
610 fatal();
611 }
612 return FileName(docfilename);
613 }
614
615 extern (D) void setDocfile()
616 {
617 docfile = setOutfilename(global.params.ddoc.name, global.params.ddoc.dir, arg, doc_ext);
618 }
619
620 /**
621 * Trigger the relevant semantic error when a file cannot be read
622 *
623 * We special case `object.d` as a failure is likely to be a rare
624 * but difficult to diagnose case for the user. Packages also require
625 * special handling to avoid exposing the compiler's internals.
626 *
627 * Params:
628 * loc = The location at which the file read originated (e.g. import)
629 */
630 private void onFileReadError(Loc loc)
631 {
632 const name = srcfile.toString();
633 if (FileName.equals(name, "object.d"))
634 {
635 ObjectNotFound(Loc.initial, ident);
636 }
637 else if (FileName.ext(this.arg) || !loc.isValid())
638 {
639 // Modules whose original argument name has an extension, or do not
640 // have a valid location come from the command-line.
641 // Error that their file cannot be found and return early.
642 .error(loc, "cannot find input file `%.*s`", cast(int)name.length, name.ptr);
643 }
644 else
645 {
646 // if module is not named 'package' but we're trying to read 'package.d', we're looking for a package module
647 bool isPackageMod = (strcmp(toChars(), "package") != 0) && isPackageFileName(srcfile);
648 if (isPackageMod)
649 .error(loc, "importing package '%s' requires a 'package.d' file which cannot be found in '%.*s'", toChars(), cast(int)name.length, name.ptr);
650 else
651 {
652 .error(loc, "unable to read module `%s`", toChars());
653 const pkgfile = FileName.combine(FileName.sansExt(name), package_d);
654 .errorSupplemental(loc, "Expected '%.*s' or '%.*s' in one of the following import paths:",
655 cast(int)name.length, name.ptr, cast(int)pkgfile.length, pkgfile.ptr);
656 }
657 }
658 if (!global.gag)
659 {
660 /* Print path
661 */
662 if (global.path.length)
663 {
664 foreach (i, p; global.path[])
665 fprintf(stderr, "import path[%llu] = %s\n", cast(ulong)i, p.path);
666 }
667 else
668 {
669 fprintf(stderr, "Specify path to file '%.*s' with -I switch\n", cast(int)name.length, name.ptr);
670 }
671
672 removeHdrFilesAndFail(global.params, Module.amodules);
673 }
674 }
675
676 /**
677 * Reads the file from `srcfile` and loads the source buffer.
678 *
679 * If makefile module dependency is requested, we add this module
680 * to the list of dependencies from here.
681 *
682 * Params:
683 * loc = the location
684 *
685 * Returns: `true` if successful
686 */
687 bool read(Loc loc)
688 {
689 if (this.src)
690 return true; // already read
691
692 //printf("Module::read('%s') file '%s'\n", toChars(), srcfile.toChars());
693
694 /* Preprocess the file if it's a .c file
695 */
696 FileName filename = srcfile;
697
698 const(ubyte)[] srctext;
699 if (global.preprocess &&
700 FileName.equalsExt(srcfile.toString(), c_ext) &&
701 FileName.exists(srcfile.toString()))
702 {
703 /* Apply C preprocessor to the .c file, returning the contents
704 * after preprocessing
705 */
706 srctext = global.preprocess(srcfile, loc, defines).data;
707 }
708 else
709 srctext = global.fileManager.getFileContents(filename);
710 this.src = srctext;
711
712 if (srctext)
713 {
714 if (global.params.makeDeps.doOutput)
715 global.params.makeDeps.files.push(srcfile.toChars());
716 return true;
717 }
718
719 this.onFileReadError(loc);
720 return false;
721 }
722
723 /// syntactic parse
724 Module parse()
725 {
726 return parseModule!ASTCodegen();
727 }
728
729 /// ditto
730 extern (D) Module parseModule(AST)()
731 {
732 const(char)* srcname = srcfile.toChars();
733 //printf("Module::parse(srcname = '%s')\n", srcname);
734
735 import dmd.timetrace;
736 timeTraceBeginEvent(TimeTraceEventType.parse);
737 scope (exit) timeTraceEndEvent(TimeTraceEventType.parse, this);
738
739 isPackageFile = isPackageFileName(srcfile);
740 const(char)[] buf = processSource(src, this);
741 // an error happened on UTF conversion
742 if (buf is null) return null;
743
744 /* If it starts with the string "Ddoc", then it's a documentation
745 * source file.
746 */
747 if (buf.length>= 4 && buf[0..4] == "Ddoc")
748 {
749 comment = buf.ptr + 4;
750 filetype = FileType.ddoc;
751 if (!docfile)
752 setDocfile();
753 return this;
754 }
755 /* If it has the extension ".dd", it is also a documentation
756 * source file. Documentation source files may begin with "Ddoc"
757 * but do not have to if they have the .dd extension.
758 * https://issues.dlang.org/show_bug.cgi?id=15465
759 */
760 if (FileName.equalsExt(arg, dd_ext))
761 {
762 comment = buf.ptr; // the optional Ddoc, if present, is handled above.
763 filetype = FileType.ddoc;
764 if (!docfile)
765 setDocfile();
766 return this;
767 }
768 /* If it has the extension ".di", it is a "header" file.
769 */
770 if (FileName.equalsExt(arg, hdr_ext))
771 filetype = FileType.dhdr;
772
773 /// Promote `this` to a root module if requested via `-i`
774 void checkCompiledImport()
775 {
776 if (!this.isRoot() && Compiler.onImport(this))
777 this.importedFrom = this;
778 }
779
780 DsymbolTable dst;
781 Package ppack = null;
782
783 /* If it has the extension ".c", it is a "C" file.
784 * If it has the extension ".i", it is a preprocessed "C" file.
785 */
786 if (FileName.equalsExt(arg, c_ext) || FileName.equalsExt(arg, i_ext))
787 {
788 filetype = FileType.c;
789
790 global.compileEnv.masm = target.os == Target.OS.Windows; // Microsoft inline assembler format
791 scope p = new CParser!AST(this, buf, cast(bool) docfile, global.errorSink, target.c, &defines, &global.compileEnv);
792 global.compileEnv.masm = false;
793 p.nextToken();
794 checkCompiledImport();
795 members = p.parseModule();
796 assert(!p.md); // C doesn't have module declarations
797 numlines = p.linnum;
798 }
799 else
800 {
801 const bool doUnittests = global.params.parsingUnittestsRequired();
802 scope p = new Parser!AST(this, buf, cast(bool) docfile, global.errorSink, &global.compileEnv, doUnittests);
803 p.nextToken();
804 p.parseModuleDeclaration();
805 md = p.md;
806
807 if (md)
808 {
809 /* A ModuleDeclaration, md, was provided.
810 * The ModuleDeclaration sets the packages this module appears in, and
811 * the name of this module.
812 */
813 this.ident = md.id;
814 dst = Package.resolve(md.packages, &this.parent, &ppack);
815 }
816
817 // Done after parsing the module header because `module x.y.z` may override the file name
818 checkCompiledImport();
819
820 members = p.parseModuleContent();
821 numlines = p.linnum;
822 }
823
824 /* The symbol table into which the module is to be inserted.
825 */
826
827 if (md)
828 {
829 // Mark the package path as accessible from the current module
830 // https://issues.dlang.org/show_bug.cgi?id=21661
831 // Code taken from Import.addPackageAccess()
832 if (md.packages.length > 0)
833 {
834 // module a.b.c.d;
835 auto p = ppack; // a
836 addAccessiblePackage(p, Visibility(Visibility.Kind.private_));
837 foreach (id; md.packages[1 .. $]) // [b, c]
838 {
839 p = cast(Package) p.symtab.lookup(id);
840 if (p is null)
841 break;
842 addAccessiblePackage(p, Visibility(Visibility.Kind.private_));
843 }
844 }
845 assert(dst);
846 Module m = ppack ? ppack.isModule() : null;
847 if (m && !isPackageFileName(m.srcfile))
848 {
849 .error(md.loc, "package name '%s' conflicts with usage as a module name in file %s", ppack.toPrettyChars(), m.srcfile.toChars());
850 }
851 }
852 else
853 {
854 /* The name of the module is set to the source file name.
855 * There are no packages.
856 */
857 dst = modules; // and so this module goes into global module symbol table
858 /* Check to see if module name is a valid identifier
859 */
860 if (!Identifier.isValidIdentifier(this.ident.toChars()))
861 error(loc, "%s `%s` has non-identifier characters in filename, use module declaration instead", kind, toPrettyChars);
862 }
863 // Insert module into the symbol table
864 Dsymbol s = this;
865 if (isPackageFile)
866 {
867 /* If the source tree is as follows:
868 * pkg/
869 * +- package.d
870 * +- common.d
871 * the 'pkg' will be incorporated to the internal package tree in two ways:
872 * import pkg;
873 * and:
874 * import pkg.common;
875 *
876 * If both are used in one compilation, 'pkg' as a module (== pkg/package.d)
877 * and a package name 'pkg' will conflict each other.
878 *
879 * To avoid the conflict:
880 * 1. If preceding package name insertion had occurred by Package::resolve,
881 * reuse the previous wrapping 'Package' if it exists
882 * 2. Otherwise, 'package.d' wrapped by 'Package' is inserted to the internal tree in here.
883 *
884 * Then change Package::isPkgMod to PKG.module_ and set Package::mod.
885 *
886 * Note that the 'wrapping Package' is the Package that contains package.d and other submodules,
887 * the one inserted to the symbol table.
888 */
889 auto ps = dst.lookup(ident);
890 Package p = ps ? ps.isPackage() : null;
891 if (p is null)
892 {
893 p = new Package(Loc.initial, ident);
894 p.tag = this.tag; // reuse the same package tag
895 p.symtab = new DsymbolTable();
896 }
897 this.tag = p.tag; // reuse the 'older' package tag
898 this.pkg = p;
899 p.parent = this.parent;
900 p.isPkgMod = PKG.module_;
901 p.mod = this;
902 s = p;
903 }
904 if (!dst.insert(s))
905 {
906 /* It conflicts with a name that is already in the symbol table.
907 * Figure out what went wrong, and issue error message.
908 */
909 Dsymbol prev = dst.lookup(ident);
910 assert(prev);
911 if (Module mprev = prev.isModule())
912 {
913 if (!FileName.equals(srcname, mprev.srcfile.toChars()))
914 error(loc, "%s `%s` from file %s conflicts with another module %s from file %s", kind, toPrettyChars, srcname, mprev.toChars(), mprev.srcfile.toChars());
915 else if (isRoot() && mprev.isRoot())
916 error(loc, "%s `%s` from file %s is specified twice on the command line", kind, toPrettyChars, srcname);
917 else
918 error(loc, "%s `%s` from file %s must be imported with 'import %s;'", kind, toPrettyChars, srcname, toPrettyChars());
919 // https://issues.dlang.org/show_bug.cgi?id=14446
920 // Return previously parsed module to avoid AST duplication ICE.
921 return mprev;
922 }
923 else if (Package pkg = prev.isPackage())
924 {
925 // 'package.d' loaded after a previous 'Package' insertion
926 if (isPackageFile)
927 amodules.push(this); // Add to global array of all modules
928 else
929 error(md ? md.loc : loc, "%s `%s` from file %s conflicts with package name %s", kind, toPrettyChars, srcname, pkg.toChars());
930 }
931 else
932 assert(global.errors);
933 }
934 else
935 {
936 // Add to global array of all modules
937 amodules.push(this);
938 }
939 Compiler.onParseModule(this);
940 return this;
941 }
942
943 /**********************************
944 * Determine if we need to generate an instance of ModuleInfo
945 * for this Module.
946 */
947 int needModuleInfo()
948 {
949 //printf("needModuleInfo() %s, %d, %d\n", toChars(), needmoduleinfo, global.params.cov);
950 return needmoduleinfo || global.params.cov;
951 }
952
953 /*******************************************
954 * Print deprecation warning if we're deprecated, when
955 * this module is imported from scope sc.
956 *
957 * Params:
958 * sc = the scope into which we are imported
959 * loc = the location of the import statement
960 */
961 void checkImportDeprecation(Loc loc, Scope* sc)
962 {
963 if (md && md.isdeprecated && !sc.isDeprecated)
964 {
965 Expression msg = md.msg;
966 if (StringExp se = msg ? msg.toStringExp() : null)
967 {
968 const slice = se.peekString();
969 if (slice.length)
970 {
971 deprecation(loc, "%s `%s` is deprecated - %.*s", kind, toPrettyChars, cast(int)slice.length, slice.ptr);
972 return;
973 }
974 }
975 deprecation(loc, "%s `%s` is deprecated", kind, toPrettyChars);
976 }
977 }
978
979 override bool isPackageAccessible(Package p, Visibility visibility, SearchOptFlags flags = SearchOpt.all)
980 {
981 if (insearch) // don't follow import cycles
982 return false;
983 insearch = true;
984 scope (exit)
985 insearch = false;
986 if (flags & SearchOpt.ignorePrivateImports)
987 visibility = Visibility(Visibility.Kind.public_); // only consider public imports
988 return super.isPackageAccessible(p, visibility);
989 }
990
991 override Dsymbol symtabInsert(Dsymbol s)
992 {
993 searchCacheIdent = null; // symbol is inserted, so invalidate cache
994 return Package.symtabInsert(s);
995 }
996
997 extern (D) void deleteObjFile()
998 {
999 if (global.params.obj)
1000 File.remove(objfile.toChars());
1001 if (docfile)
1002 File.remove(docfile.toChars());
1003 }
1004
1005 /*******************************************
1006 * Can't run semantic on s now, try again later.
1007 */
1008 extern (D) static void addDeferredSemantic(Dsymbol s)
1009 {
1010 //printf("Module::addDeferredSemantic('%s')\n", s.toChars());
1011 if (!deferred.contains(s))
1012 deferred.push(s);
1013 }
1014
1015 extern (D) static void addDeferredSemantic2(Dsymbol s)
1016 {
1017 //printf("Module::addDeferredSemantic2('%s')\n", s.toChars());
1018 if (!deferred2.contains(s))
1019 deferred2.push(s);
1020 }
1021
1022 extern (D) static void addDeferredSemantic3(Dsymbol s)
1023 {
1024 //printf("Module::addDeferredSemantic3('%s')\n", s.toChars());
1025 if (!deferred.contains(s))
1026 deferred3.push(s);
1027 }
1028
1029 /******************************************
1030 * Run semantic() on deferred symbols.
1031 */
1032 static void runDeferredSemantic()
1033 {
1034 __gshared int nested;
1035 if (nested)
1036 return;
1037 //if (deferred.length) printf("+Module::runDeferredSemantic(), len = %ld\n", deferred.length);
1038 nested++;
1039
1040 size_t len;
1041 do
1042 {
1043 len = deferred.length;
1044 if (!len)
1045 break;
1046
1047 Dsymbol* todo;
1048 Dsymbol* todoalloc = null;
1049 Dsymbol tmp;
1050 if (len == 1)
1051 {
1052 todo = &tmp;
1053 }
1054 else
1055 {
1056 todo = cast(Dsymbol*)Mem.check(malloc(len * Dsymbol.sizeof));
1057 todoalloc = todo;
1058 }
1059 memcpy(todo, deferred.tdata(), len * Dsymbol.sizeof);
1060 deferred.setDim(0);
1061
1062 foreach (i; 0..len)
1063 {
1064 Dsymbol s = todo[i];
1065 s.dsymbolSemantic(null);
1066 //printf("deferred: %s, parent = %s\n", s.toChars(), s.parent.toChars());
1067 }
1068 //printf("\tdeferred.length = %ld, len = %ld\n", deferred.length, len);
1069 if (todoalloc)
1070 free(todoalloc);
1071 }
1072 while (deferred.length != len); // while making progress
1073 nested--;
1074 //printf("-Module::runDeferredSemantic(), len = %ld\n", deferred.length);
1075 }
1076
1077 static void runDeferredSemantic2()
1078 {
1079 Module.runDeferredSemantic();
1080
1081 Dsymbols* a = &Module.deferred2;
1082 for (size_t i = 0; i < a.length; i++)
1083 {
1084 Dsymbol s = (*a)[i];
1085 //printf("[%d] %s semantic2a\n", i, s.toPrettyChars());
1086 s.semantic2(null);
1087
1088 if (global.errors)
1089 break;
1090 }
1091 a.setDim(0);
1092 }
1093
1094 static void runDeferredSemantic3()
1095 {
1096 Module.runDeferredSemantic2();
1097
1098 Dsymbols* a = &Module.deferred3;
1099 for (size_t i = 0; i < a.length; i++)
1100 {
1101 Dsymbol s = (*a)[i];
1102 //printf("[%d] %s semantic3a\n", i, s.toPrettyChars());
1103 s.semantic3(null);
1104
1105 if (global.errors)
1106 break;
1107 }
1108 a.setDim(0);
1109 }
1110
1111 extern (D) static void clearCache() nothrow
1112 {
1113 foreach (Module m; amodules)
1114 m.searchCacheIdent = null;
1115 }
1116
1117 /************************************
1118 * Recursively look at every module this module imports,
1119 * return true if it imports m.
1120 * Can be used to detect circular imports.
1121 */
1122 int imports(Module m) nothrow
1123 {
1124 //printf("%s Module::imports(%s)\n", toChars(), m.toChars());
1125 version (none)
1126 {
1127 foreach (i, Module mi; aimports)
1128 printf("\t[%d] %s\n", cast(int) i, mi.toChars());
1129 }
1130 foreach (Module mi; aimports)
1131 {
1132 if (mi == m)
1133 return true;
1134 if (!mi.insearch)
1135 {
1136 mi.insearch = true;
1137 int r = mi.imports(m);
1138 if (r)
1139 return r;
1140 }
1141 }
1142 return false;
1143 }
1144
1145 bool isRoot() nothrow
1146 {
1147 return this.importedFrom == this;
1148 }
1149
1150 /// Returns: Whether this module is in the `core` package and has name `ident`
1151 bool isCoreModule(Identifier ident) nothrow
1152 {
1153 return this.ident == ident && parent && parent.ident == Id.core && !parent.parent;
1154 }
1155
1156 // Back end
1157 int doppelganger; // sub-module
1158 Symbol* cov; // private uint[] __coverage;
1159 uint[] covb; // bit array of valid code line numbers
1160 Symbol* sictor; // module order independent constructor
1161 Symbol* sctor; // module constructor
1162 Symbol* sdtor; // module destructor
1163 Symbol* ssharedctor; // module shared constructor
1164 Symbol* sshareddtor; // module shared destructor
1165 Symbol* stest; // module unit test
1166 Symbol* sfilename; // symbol for filename
1167
1168 uint[uint] ctfe_cov; /// coverage information from ctfe execution_count[line]
1169
1170 override void accept(Visitor v)
1171 {
1172 v.visit(this);
1173 }
1174
1175 /***********************************************
1176 * Writes this module's fully-qualified name to buf
1177 * Params:
1178 * buf = The buffer to write to
1179 */
1180 void fullyQualifiedName(ref OutBuffer buf) nothrow
1181 {
1182 buf.writestring(ident.toString());
1183
1184 for (auto package_ = parent; package_ !is null; package_ = package_.parent)
1185 {
1186 buf.prependstring(".");
1187 buf.prependstring(package_.ident.toChars());
1188 }
1189 }
1190
1191 /** Lazily initializes and returns the escape table.
1192 Turns out it eats a lot of memory.
1193 */
1194 extern(D) Escape* escapetable() nothrow
1195 {
1196 if (!_escapetable)
1197 _escapetable = new Escape();
1198 return _escapetable;
1199 }
1200
1201 /****************************
1202 * A Singleton that loads core.stdc.config
1203 * Returns:
1204 * Module of core.stdc.config, null if couldn't find it
1205 */
1206 extern (D) static Module loadCoreStdcConfig()
1207 {
1208 __gshared Module core_stdc_config;
1209 auto pkgids = new Identifier[2];
1210 pkgids[0] = Id.core;
1211 pkgids[1] = Id.stdc;
1212 return loadModuleFromLibrary(core_stdc_config, pkgids, Id.config);
1213 }
1214
1215 /****************************
1216 * A Singleton that loads core.atomic
1217 * Returns:
1218 * Module of core.atomic, null if couldn't find it
1219 */
1220 extern (D) static Module loadCoreAtomic()
1221 {
1222 __gshared Module core_atomic;
1223 auto pkgids = new Identifier[1];
1224 pkgids[0] = Id.core;
1225 return loadModuleFromLibrary(core_atomic, pkgids, Id.atomic);
1226 }
1227
1228 /****************************
1229 * A Singleton that loads std.math
1230 * Returns:
1231 * Module of std.math, null if couldn't find it
1232 */
1233 extern (D) static Module loadStdMath()
1234 {
1235 __gshared Module std_math;
1236 auto pkgids = new Identifier[1];
1237 pkgids[0] = Id.std;
1238 return loadModuleFromLibrary(std_math, pkgids, Id.math);
1239 }
1240
1241 /**********************************
1242 * Load a Module from the library.
1243 * Params:
1244 * mod = cached return value of this call
1245 * pkgids = package identifiers
1246 * modid = module id
1247 * Returns:
1248 * Module loaded, null if cannot load it
1249 */
1250 extern (D) private static Module loadModuleFromLibrary(ref Module mod, Identifier[] pkgids, Identifier modid)
1251 {
1252 if (mod)
1253 return mod;
1254
1255 auto imp = new Import(Loc.initial, pkgids[], modid, null, true);
1256 // Module.load will call fatal() if there's no module available.
1257 // Gag the error here, pushing the error handling to the caller.
1258 const errors = global.startGagging();
1259 imp.load(null);
1260 if (imp.mod)
1261 {
1262 imp.mod.importAll(null);
1263 imp.mod.dsymbolSemantic(null);
1264 }
1265 global.endGagging(errors);
1266 mod = imp.mod;
1267 return mod;
1268 }
1269 }
1270
1271 /***********************************************************
1272 */
1273 extern (C++) struct ModuleDeclaration
1274 {
1275 Loc loc;
1276 Identifier id;
1277 Identifier[] packages; // array of Identifier's representing packages
1278 bool isdeprecated; // if it is a deprecated module
1279 Expression msg;
1280
1281 extern (D) this(Loc loc, Identifier[] packages, Identifier id, Expression msg, bool isdeprecated) @safe
1282 {
1283 this.loc = loc;
1284 this.packages = packages;
1285 this.id = id;
1286 this.msg = msg;
1287 this.isdeprecated = isdeprecated;
1288 }
1289
1290 extern (C++) const(char)* toChars() const @safe
1291 {
1292 OutBuffer buf;
1293 foreach (pid; packages)
1294 {
1295 buf.writestring(pid.toString());
1296 buf.writeByte('.');
1297 }
1298 buf.writestring(id.toString());
1299 return buf.extractChars();
1300 }
1301
1302 /// Provide a human readable representation
1303 extern (D) const(char)[] toString() const
1304 {
1305 return this.toChars().toDString;
1306 }
1307 }
1308
1309 /****************************************
1310 * Create array of the local classes in the Module, suitable
1311 * for inclusion in ModuleInfo
1312 * Params:
1313 * mod = the Module
1314 * aclasses = array to fill in
1315 * Returns: array of local classes
1316 */
1317 void getLocalClasses(Module mod, ref ClassDeclarations aclasses)
1318 {
1319 //printf("members.length = %d\n", mod.members.length);
1320 int pushAddClassDg(size_t n, Dsymbol sm)
1321 {
1322 if (!sm)
1323 return 0;
1324
1325 if (auto cd = sm.isClassDeclaration())
1326 {
1327 // compatibility with previous algorithm
1328 if (cd.parent && cd.parent.isTemplateMixin())
1329 return 0;
1330
1331 if (cd.classKind != ClassKind.objc)
1332 aclasses.push(cd);
1333 }
1334 return 0;
1335 }
1336
1337 _foreach(null, mod.members, &pushAddClassDg);
1338 }
1339
1340
1341 alias ForeachDg = int delegate(size_t idx, Dsymbol s);
1342
1343 /***************************************
1344 * Expands attribute declarations in members in depth first
1345 * order. Calls dg(size_t symidx, Dsymbol *sym) for each
1346 * member.
1347 * If dg returns !=0, stops and returns that value else returns 0.
1348 * Use this function to avoid the O(N + N^2/2) complexity of
1349 * calculating dim and calling N times getNth.
1350 * Returns:
1351 * last value returned by dg()
1352 */
1353 int _foreach(Scope* sc, Dsymbols* members, scope ForeachDg dg, size_t* pn = null)
1354 {
1355 assert(dg);
1356 if (!members)
1357 return 0;
1358 size_t n = pn ? *pn : 0; // take over index
1359 int result = 0;
1360 foreach (size_t i; 0 .. members.length)
1361 {
1362 import dmd.attrib : AttribDeclaration;
1363 import dmd.dtemplate : TemplateMixin;
1364
1365 Dsymbol s = (*members)[i];
1366 if (AttribDeclaration a = s.isAttribDeclaration())
1367 result = _foreach(sc, a.include(sc), dg, &n);
1368 else if (TemplateMixin tm = s.isTemplateMixin())
1369 result = _foreach(sc, tm.members, dg, &n);
1370 else if (s.isTemplateInstance())
1371 {
1372 }
1373 else if (s.isUnitTestDeclaration())
1374 {
1375 }
1376 else
1377 result = dg(n++, s);
1378 if (result)
1379 break;
1380 }
1381 if (pn)
1382 *pn = n; // update index
1383 return result;
1384 }
1385
1386 /**
1387 * Process the content of a source file
1388 *
1389 * Attempts to find which encoding it is using, if it has BOM,
1390 * and then normalize the source to UTF-8. If no encoding is required,
1391 * a slice of `src` will be returned without extra allocation.
1392 *
1393 * Params:
1394 * src = Content of the source file to process
1395 * mod = Module matching `src`, used for error handling
1396 *
1397 * Returns:
1398 * UTF-8 encoded variant of `src`, stripped of any BOM,
1399 * or `null` if an error happened.
1400 */
1401 private const(char)[] processSource (const(ubyte)[] src, Module mod)
1402 {
1403 enum SourceEncoding { utf16, utf32}
1404 enum Endian { little, big}
1405 immutable loc = mod.loc;
1406
1407 /*
1408 * Convert a buffer from UTF32 to UTF8
1409 * Params:
1410 * Endian = is the buffer big/little endian
1411 * buf = buffer of UTF32 data
1412 * Returns:
1413 * input buffer reencoded as UTF8
1414 */
1415
1416 char[] UTF32ToUTF8(Endian endian)(const(char)[] buf)
1417 {
1418 static if (endian == Endian.little)
1419 alias readNext = Port.readlongLE;
1420 else
1421 alias readNext = Port.readlongBE;
1422
1423 if (buf.length & 3)
1424 {
1425 .error(loc, "%s `%s` odd length of UTF-32 char source %llu",
1426 mod.kind, mod.toPrettyChars, cast(ulong) buf.length);
1427 return null;
1428 }
1429
1430 const (uint)[] eBuf = cast(const(uint)[])buf;
1431
1432 OutBuffer dbuf;
1433 dbuf.reserve(eBuf.length);
1434
1435 foreach (i; 0 .. eBuf.length)
1436 {
1437 const u = readNext(&eBuf[i]);
1438 if (u & ~0x7F)
1439 {
1440 if (u > 0x10FFFF)
1441 {
1442 .error(loc, "%s `%s` UTF-32 value %08x greater than 0x10FFFF", mod.kind, mod.toPrettyChars, u);
1443 return null;
1444 }
1445 dbuf.writeUTF8(u);
1446 }
1447 else
1448 dbuf.writeByte(u);
1449 }
1450 dbuf.writeByte(0); //add null terminator
1451 return dbuf.extractSlice();
1452 }
1453
1454 /*
1455 * Convert a buffer from UTF16 to UTF8
1456 * Params:
1457 * Endian = is the buffer big/little endian
1458 * buf = buffer of UTF16 data
1459 * Returns:
1460 * input buffer reencoded as UTF8
1461 */
1462
1463 char[] UTF16ToUTF8(Endian endian)(const(char)[] buf)
1464 {
1465 static if (endian == Endian.little)
1466 alias readNext = Port.readwordLE;
1467 else
1468 alias readNext = Port.readwordBE;
1469
1470 if (buf.length & 1)
1471 {
1472 .error(loc, "%s `%s` odd length of UTF-16 char source %llu", mod.kind, mod.toPrettyChars, cast(ulong) buf.length);
1473 return null;
1474 }
1475
1476 const (ushort)[] eBuf = cast(const(ushort)[])buf;
1477
1478 OutBuffer dbuf;
1479 dbuf.reserve(eBuf.length);
1480
1481 //i will be incremented in the loop for high codepoints
1482 foreach (ref i; 0 .. eBuf.length)
1483 {
1484 uint u = readNext(&eBuf[i]);
1485 if (u & ~0x7F)
1486 {
1487 if (0xD800 <= u && u < 0xDC00)
1488 {
1489 i++;
1490 if (i >= eBuf.length)
1491 {
1492 .error(loc, "%s `%s` surrogate UTF-16 high value %04x at end of file", mod.kind, mod.toPrettyChars, u);
1493 return null;
1494 }
1495 const u2 = readNext(&eBuf[i]);
1496 if (u2 < 0xDC00 || 0xE000 <= u2)
1497 {
1498 .error(loc, "%s `%s` surrogate UTF-16 low value %04x out of range", mod.kind, mod.toPrettyChars, u2);
1499 return null;
1500 }
1501 u = (u - 0xD7C0) << 10;
1502 u |= (u2 - 0xDC00);
1503 }
1504 else if (u >= 0xDC00 && u <= 0xDFFF)
1505 {
1506 .error(loc, "%s `%s` unpaired surrogate UTF-16 value %04x", mod.kind, mod.toPrettyChars, u);
1507 return null;
1508 }
1509 else if (u == 0xFFFE || u == 0xFFFF)
1510 {
1511 .error(loc, "%s `%s` illegal UTF-16 value %04x", mod.kind, mod.toPrettyChars, u);
1512 return null;
1513 }
1514 dbuf.writeUTF8(u);
1515 }
1516 else
1517 dbuf.writeByte(u);
1518 }
1519 dbuf.writeByte(0); //add a terminating null byte
1520 return dbuf.extractSlice();
1521 }
1522
1523 const(char)[] buf = cast(const(char)[]) src;
1524
1525 // Assume the buffer is from memory and has not be read from disk. Assume UTF-8.
1526 if (buf.length < 2)
1527 return buf;
1528
1529 /* Convert all non-UTF-8 formats to UTF-8.
1530 * BOM : https://www.unicode.org/faq/utf_bom.html
1531 * 00 00 FE FF UTF-32BE, big-endian
1532 * FF FE 00 00 UTF-32LE, little-endian
1533 * FE FF UTF-16BE, big-endian
1534 * FF FE UTF-16LE, little-endian
1535 * EF BB BF UTF-8
1536 */
1537 if (buf[0] == 0xFF && buf[1] == 0xFE)
1538 {
1539 if (buf.length >= 4 && buf[2] == 0 && buf[3] == 0)
1540 return UTF32ToUTF8!(Endian.little)(buf[4 .. $]);
1541 return UTF16ToUTF8!(Endian.little)(buf[2 .. $]);
1542 }
1543
1544 if (buf[0] == 0xFE && buf[1] == 0xFF)
1545 return UTF16ToUTF8!(Endian.big)(buf[2 .. $]);
1546
1547 if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0xFE && buf[3] == 0xFF)
1548 return UTF32ToUTF8!(Endian.big)(buf[4 .. $]);
1549
1550 if (buf.length >= 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF)
1551 return buf[3 .. $];
1552
1553 /* There is no BOM. Make use of Arcane Jill's insight that
1554 * the first char of D source must be ASCII to
1555 * figure out the encoding.
1556 */
1557 if (buf.length >= 4 && buf[1] == 0 && buf[2] == 0 && buf[3] == 0)
1558 return UTF32ToUTF8!(Endian.little)(buf);
1559 if (buf.length >= 4 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0)
1560 return UTF32ToUTF8!(Endian.big)(buf);
1561 // try to check for UTF-16
1562 if (buf.length >= 2 && buf[1] == 0)
1563 return UTF16ToUTF8!(Endian.little)(buf);
1564 if (buf[0] == 0)
1565 return UTF16ToUTF8!(Endian.big)(buf);
1566
1567 // It's UTF-8
1568 if (buf[0] >= 0x80)
1569 {
1570 .error(loc, "%s `%s` source file must start with BOM or ASCII character, not \\x%02X", mod.kind, mod.toPrettyChars, buf[0]);
1571 return null;
1572 }
1573
1574 return buf;
1575 }
1576
1577 /*******************************************
1578 * Look for member of the form:
1579 * const(MemberInfo)[] getMembers(string);
1580 * Returns NULL if not found
1581 */
1582 FuncDeclaration findGetMembers(ScopeDsymbol dsym)
1583 {
1584 import dmd.opover : search_function;
1585 Dsymbol s = search_function(dsym, Id.getmembers);
1586 FuncDeclaration fdx = s ? s.isFuncDeclaration() : null;
1587 version (none)
1588 {
1589 // Finish
1590 __gshared TypeFunction tfgetmembers;
1591 if (!tfgetmembers)
1592 {
1593 Scope sc;
1594 sc.eSink = global.errorSink;
1595 auto parameters = new Parameters();
1596 Parameters* p = new Parameter(STC.in_, Type.tchar.constOf().arrayOf(), null, null);
1597 parameters.push(p);
1598 Type tret = null;
1599 TypeFunction tf = new TypeFunction(parameters, tret, VarArg.none, LINK.d);
1600 tfgetmembers = tf.dsymbolSemantic(Loc.initial, &sc).isTypeFunction();
1601 }
1602 if (fdx)
1603 fdx = fdx.overloadExactMatch(tfgetmembers);
1604 }
1605 if (fdx && fdx.isVirtual())
1606 fdx = null;
1607 return fdx;
1608 }