for review: add nested modules [3/5]

Fergus Henderson fjh at cs.mu.OZ.AU
Thu Feb 26 16:32:21 AEDT 1998


+write_dependency_file(Module, MaybeTransOptDeps) -->
+	{ Module = module_imports(ModuleName, ParentDeps, IntDeps, ImplDeps,
+			IndirectDeps, _InclDeps, FactDeps0, _Items, _Error) },
 	globals__io_lookup_bool_option(verbose, Verbose),
-	{ string__append(ModuleName, ".d", DependencyFileName) },
+	{ module_name_to_file_name(ModuleName, BaseFileName) },
+	{ string__append(BaseFileName, ".d", DependencyFileName) },
 	maybe_write_string(Verbose, "% Writing auto-dependency file `"),
 	maybe_write_string(Verbose, DependencyFileName),
 	maybe_write_string(Verbose, "'..."),
 	maybe_flush_output(Verbose),
 	io__open_output(DependencyFileName, Result),
 	( { Result = ok(DepStream) } ->
+		{ list__append(IntDeps, ImplDeps, LongDeps0) },
+		{ ShortDeps0 = IndirectDeps },
 		{ set__list_to_set(LongDeps0, LongDepsSet0) },
 		{ set__delete(LongDepsSet0, ModuleName, LongDepsSet) },
 		{ set__list_to_set(ShortDeps0, ShortDepsSet0) },
@@ -535,7 +1001,7 @@
 			% this exact pattern
 			%
 			io__write_strings(DepStream,
-				[ModuleName, ".trans_opt_date :"]),
+				[BaseFileName, ".trans_opt_date :"]),
 			write_dependencies_list(TransOptDateDeps, ".trans_opt", 
 				DepStream)
 		;
@@ -544,29 +1010,29 @@
 
 		( { FactDeps \= [] } ->
 			io__write_strings(DepStream, 
-				["\n\n", ModuleName, ".fact_tables ="]),
-			write_dependencies_list(FactDeps, "", DepStream),
+				["\n\n", BaseFileName, ".fact_tables ="]),
+			write_file_dependencies_list(FactDeps, "", DepStream),
 			io__nl(DepStream),
 			globals__io_lookup_bool_option(assume_gmake,
 				AssumeGmake),
 			( { AssumeGmake = no } ->
 				io__write_strings(DepStream,
-					[ModuleName, ".fact_tables.os ="]),
-				write_dependencies_list(FactDeps, ".o",
+					[BaseFileName, ".fact_tables.os ="]),
+				write_file_dependencies_list(FactDeps, ".o",
 					DepStream),
 				io__write_strings(DepStream, [
 					"\n\n", 
-					ModuleName, ".fact_tables.cs ="]),
-				write_dependencies_list(FactDeps, ".c",
+					BaseFileName, ".fact_tables.cs ="]),
+				write_file_dependencies_list(FactDeps, ".c",
 					DepStream),
 				io__nl(DepStream)
 			;
 				io__write_strings(DepStream, [
-					"\n\n", ModuleName,
-					".fact_tables.os = $(", ModuleName,
+					"\n\n", BaseFileName,
+					".fact_tables.os = $(", BaseFileName,
 					".fact_tables:%=%.o)\n\n",
-					ModuleName,
-					".fact_tables.cs = $(", ModuleName,
+					BaseFileName,
+					".fact_tables.cs = $(", BaseFileName,
 					".fact_tables:%=%.c)\n\n"
 				])
 			)
@@ -575,24 +1041,25 @@
 		),
 
 		io__write_strings(DepStream, ["\n\n",
-			ModuleName, ".optdate ",
-			ModuleName, ".trans_opt_date ",
-			ModuleName, ".c ",
-			ModuleName, ".err ",
-			ModuleName, ".o : ",
-			ModuleName, ".m"
+			BaseFileName, ".optdate ",
+			BaseFileName, ".trans_opt_date ",
+			BaseFileName, ".c ",
+			BaseFileName, ".err ",
+			BaseFileName, ".o : ",
+			BaseFileName, ".m"
 		] ),
+		write_dependencies_list(ParentDeps, ".int0", DepStream),
 		write_dependencies_list(LongDeps, ".int", DepStream),
 		write_dependencies_list(ShortDeps, ".int2", DepStream),
 
 		( { FactDeps \= [] } ->
 			io__write_strings(DepStream, [
-				" \\\n\t$(", ModuleName, ".fact_tables)\n\n",
-				"$(", ModuleName, ".fact_tables.os) : $(",
-				ModuleName, ".fact_tables) ",
-				ModuleName, ".m\n\n",
-				"$(", ModuleName, ".fact_tables.cs) : ",
-				ModuleName, ".o\n"
+				" \\\n\t$(", BaseFileName, ".fact_tables)\n\n",
+				"$(", BaseFileName, ".fact_tables.os) : $(",
+				BaseFileName, ".fact_tables) ",
+				BaseFileName, ".m\n\n",
+				"$(", BaseFileName, ".fact_tables.cs) : ",
+				BaseFileName, ".o\n"
 			] )
 		;
 			[]
@@ -603,10 +1070,10 @@
 		( { Intermod = yes } ->
 			io__write_strings(DepStream, [
 				"\n\n", 
-				ModuleName, ".c ",
-				ModuleName, ".trans_opt_date ",
-				ModuleName, ".err ", 
-				ModuleName, ".o :"
+				BaseFileName, ".c ",
+				BaseFileName, ".trans_opt_date ",
+				BaseFileName, ".err ", 
+				BaseFileName, ".o :"
 			]),
 			% The .c file only depends on the .opt files from 
 			% the current directory, so that inter-module
@@ -628,9 +1095,9 @@
 					".opt", DepStream),
 				io__write_strings(DepStream, [
 					"\n\n", 
-					ModuleName, ".c ",
-					ModuleName, ".err ", 
-					ModuleName, ".o :"
+					BaseFileName, ".c ",
+					BaseFileName, ".err ", 
+					BaseFileName, ".o :"
 				]),
 				write_dependencies_list(TransOptDeps,
 					".trans_opt", DepStream)
@@ -645,19 +1112,21 @@
 		),
 
 		io__write_strings(DepStream, [
-				"\n\n", ModuleName, ".date : ",
-				ModuleName, ".m"
+				"\n\n", BaseFileName, ".date ",
+				BaseFileName, ".date0 : ",
+				BaseFileName, ".m"
 		]),
+		write_dependencies_list(ParentDeps, ".int0", DepStream),
 		write_dependencies_list(LongDeps, ".int3", DepStream),
 		write_dependencies_list(ShortDeps, ".int3", DepStream),
 
 		io__write_strings(DepStream, [
 			"\n\n",
-			ModuleName, ".dir/", ModuleName, "_000.o : ",
-				ModuleName, ".m\n",
-			"\trm -rf ", ModuleName, ".dir\n",
+			BaseFileName, ".dir/", BaseFileName, "_000.o : ",
+				BaseFileName, ".m\n",
+			"\trm -rf ", BaseFileName, ".dir\n",
 			"\t$(MCS) $(GRADEFLAGS) $(MCSFLAGS) ",
-				ModuleName, ".m\n"
+				BaseFileName, ".m\n"
 		]),
 
 		io__close_output(DepStream),
@@ -672,7 +1141,8 @@
 	globals__io_lookup_bool_option(transitive_optimization, TransOpt),
 	( { TransOpt = yes } ->
 		globals__io_lookup_bool_option(verbose, Verbose),
-		{ string__append(ModuleName, ".d", DependencyFileName) },
+		{ module_name_to_file_name(ModuleName, BaseFileName) },
+		{ string__append(BaseFileName, ".d", DependencyFileName) },
 		maybe_write_string(Verbose, "% Reading auto-dependency file `"),
 		maybe_write_string(Verbose, DependencyFileName),
 		maybe_write_string(Verbose, "'..."),
@@ -680,7 +1150,7 @@
 		io__open_input(DependencyFileName, OpenResult),
 		( { OpenResult = ok(Stream) } ->
 			io__set_input_stream(Stream, OldStream),
-			{ string__append(ModuleName, ".trans_opt_date :", 
+			{ string__append(BaseFileName, ".trans_opt_date :", 
 				TransOptFileName0) },
 			{ string__to_char_list(TransOptFileName0, 
 				TransOptFileName) },
@@ -704,7 +1174,7 @@
 		),
 		maybe_write_string(Verbose, " done.\n")
 	;
-			{ MaybeTransOptDeps = no }
+		{ MaybeTransOptDeps = no }
 	).
 			
 	% Read lines from the dependency file (module.d) until one is found
@@ -729,7 +1199,7 @@
 	% followed by a word which ends in .trans_opt.  Remove the
 	% .trans_opt ending from all the words which are read in and return
 	% the resulting list of modules..
-:- pred read_dependency_file_get_modules(list(string)::out, io__state::di,
+:- pred read_dependency_file_get_modules(list(module_name)::out, io__state::di,
 	io__state::uo) is det.
 read_dependency_file_get_modules(TransOptDeps) -->
 	io__read_line(Result),
@@ -749,7 +1219,8 @@
 			['.','t','r','a','n','s','_','o','p','t'], 
 			ModuleCharList) }
 	->
-		{ string__from_char_list(ModuleCharList, Module) },
+		{ string__from_char_list(ModuleCharList, ModuleFileName) },
+		{ file_name_to_module_name(ModuleFileName, Module) },
 		read_dependency_file_get_modules(TransOptDeps0),
 		{ TransOptDeps = [ Module | TransOptDeps0 ] }
 	;
@@ -761,12 +1232,13 @@
 	% If it exists, add it to both output lists. Otherwise, if a .opt
 	% file exists, add it to the OptDeps list, and if a .trans_opt
 	% file exists, add it to the TransOptDeps list.
-:- pred get_both_opt_deps(list(string)::in, list(string)::in, 
-	list(string)::out, list(string)::out, 
+:- pred get_both_opt_deps(list(module_name)::in, list(string)::in, 
+	list(module_name)::out, list(module_name)::out, 
 	io__state::di, io__state::uo) is det.
 get_both_opt_deps([], _, [], []) --> [].
 get_both_opt_deps([Dep | Deps], IntermodDirs, OptDeps, TransOptDeps) -->
-	{ string__append(Dep, ".m", DepName) },
+	{ module_name_to_file_name(Dep, BaseFileName) },
+	{ string__append(BaseFileName, ".m", DepName) },
 	search_for_file(IntermodDirs, DepName, Result1),
 	get_both_opt_deps(Deps, IntermodDirs, OptDeps0, TransOptDeps0),
 	( { Result1 = yes } ->
@@ -774,7 +1246,7 @@
 		{ TransOptDeps = [Dep | TransOptDeps0] },
 		io__seen
 	;
-		{ string__append(Dep, ".opt", OptName) },
+		{ string__append(BaseFileName, ".opt", OptName) },
 		search_for_file(IntermodDirs, OptName, Result2),
 		( { Result2 = yes } ->
 			{ OptDeps = [Dep | OptDeps0] },
@@ -782,7 +1254,7 @@
 		;
 			{ OptDeps = OptDeps0 }
 		),
-		{ string__append(Dep, ".trans_opt", TransOptName) },
+		{ string__append(BaseFileName, ".trans_opt", TransOptName) },
 		search_for_file(IntermodDirs, TransOptName, Result3),
 		( { Result3 = yes } ->
 			{ TransOptDeps = [Dep | TransOptDeps0] },
@@ -794,18 +1266,19 @@
 
 	% For each dependency, search intermod_directories for a .Suffix
 	% file or a .m file, filtering out those for which the search fails.
-:- pred get_opt_deps(list(string)::in, list(string)::in, string::in,
-	list(string)::out, io__state::di, io__state::uo) is det.
+:- pred get_opt_deps(list(module_name)::in, list(string)::in, string::in,
+	list(module_name)::out, io__state::di, io__state::uo) is det.
 get_opt_deps([], _, _, []) --> [].
 get_opt_deps([Dep | Deps], IntermodDirs, Suffix, OptDeps) -->
-	{ string__append(Dep, ".m", DepName) },
+	{ module_name_to_file_name(Dep, BaseFileName) },
+	{ string__append(BaseFileName, ".m", DepName) },
 	search_for_file(IntermodDirs, DepName, Result1),
 	get_opt_deps(Deps, IntermodDirs, Suffix, OptDeps0),
 	( { Result1 = yes } ->
 		{ OptDeps = [Dep | OptDeps0] },
 		io__seen
 	;
-		{ string__append(Dep, Suffix, OptName) },
+		{ string__append(BaseFileName, Suffix, OptName) },
 		search_for_file(IntermodDirs, OptName, Result2),
 		( { Result2 = yes } ->
 			{ OptDeps = [Dep | OptDeps0] },
@@ -824,37 +1297,44 @@
 	%
 	% check whether we could read the main `.m' file
 	%
-	{ map__lookup(DepsMap, Module, deps(_, Error, _, _, _)) },
+	{ map__lookup(DepsMap, Module, deps(_, ModuleImports)) },
+	{ module_imports_get_error(ModuleImports, Error) },
 	( { Error = fatal } ->
+		{ prog_out__sym_name_to_string(Module, ModuleString) },
 		{ string__append_list(["fatal error reading module `",
-			Module, "'."], Message) },
+			ModuleString, "'."], Message) },
 		report_error(Message)
 	;
 		globals__io_lookup_accumulating_option(intermod_directories, 
 			IntermodDirs),
 		generate_dependencies_write_dep_file(Module, DepsMap),
-		{ relation__init(DepsRel0) },
-		{ map__to_assoc_list(DepsMap, DepsList) },
-		{ deps_map_to_deps_rel(DepsList, DepsMap, 
-			DepsRel0, DepsRel) },
-		{ relation__atsort(DepsRel, DepsOrdering0) },
-		maybe_output_module_order(Module, DepsOrdering0),
-		{ list__map(set__to_sorted_list, DepsOrdering0, 
-			DepsOrdering) },
-		{ list__condense(DepsOrdering, TransOptDepsOrdering0) },
+		{ relation__init(IntDepsRel0) },
+		{ relation__init(ImplDepsRel0) },
+		{ map__values(DepsMap, DepsList) },
+		{ deps_list_to_deps_rel(DepsList, DepsMap, 
+			IntDepsRel0, IntDepsRel, ImplDepsRel0, ImplDepsRel) },
+		{ relation__atsort(IntDepsRel, IntDepsOrdering0) },
+		{ relation__atsort(ImplDepsRel, ImplDepsOrdering0) },
+		maybe_output_module_order(Module, ImplDepsOrdering0),
+		{ list__map(set__to_sorted_list, ImplDepsOrdering0, 
+			ImplDepsOrdering) },
+		{ list__map(set__to_sorted_list, IntDepsOrdering0, 
+			IntDepsOrdering) },
+		{ list__condense(ImplDepsOrdering, TransOptDepsOrdering0) },
 		get_opt_deps(TransOptDepsOrdering0, IntermodDirs, ".trans_opt",
 			TransOptDepsOrdering),
-		generate_dependencies_write_d_files(DepsOrdering,
+		generate_dependencies_write_d_files(IntDepsOrdering,
 			TransOptDepsOrdering, DepsMap)
 	).
 
-:- pred maybe_output_module_order(string::in, list(set(string))::in,
+:- pred maybe_output_module_order(module_name::in, list(set(module_name))::in,
 	io__state::di, io__state::uo) is det.
 maybe_output_module_order(Module, DepsOrdering) -->
 	globals__io_lookup_bool_option(generate_module_order, Order),
 	globals__io_lookup_bool_option(verbose, Verbose),
 	( { Order = yes } ->
-		{ string__append(Module, ".order", OrdFileName) },
+		{ module_name_to_file_name(Module, BaseFileName) },
+		{ string__append(BaseFileName, ".order", OrdFileName) },
 		maybe_write_string(Verbose, "% Creating module order file `"),
 		maybe_write_string(Verbose, OrdFileName),
 		maybe_write_string(Verbose, "'...\n"),
@@ -877,7 +1357,7 @@
 		io__state::di, io__state::uo) is det.
 write_module_scc(Stream, SCC0) -->
 	{ set__to_sorted_list(SCC0, SCC) },
-	io__write_list(Stream, SCC, "\n", io__write_string).
+	io__write_list(Stream, SCC, "\n", prog_out__write_sym_name).
 
 % generate_dependencies_write_d_files(Sccs, TransOptOrder, DepsMap, IO0, IO).
 %		This predicate writes out the .d files for all the modules
@@ -887,8 +1367,9 @@
 %		of the module call graph.  
 %		TransOptOrder gives the ordering that is used to determine
 %		which other modules the .trans_opt files may depend on.
-:- pred generate_dependencies_write_d_files(list(list(string))::in, 
-	list(string)::in, deps_map::in, io__state::di, io__state::uo) is det.
+:- pred generate_dependencies_write_d_files(list(list(module_name))::in, 
+	list(module_name)::in, deps_map::in,
+	io__state::di, io__state::uo) is det.
 generate_dependencies_write_d_files([], _, _) --> [].
 generate_dependencies_write_d_files([Scc | Sccs], TransOptOrder, DepsMap) --> 
 	{ list__condense([Scc | Sccs], TransDeps) },
@@ -896,16 +1377,22 @@
 		DepsMap),
 	generate_dependencies_write_d_files(Sccs, TransOptOrder, DepsMap).
 
-:- pred generate_dependencies_write_d_files_2(list(string)::in, 
-	list(string)::in, list(string)::in, deps_map::in, 
+:- pred generate_dependencies_write_d_files_2(list(module_name)::in, 
+	list(module_name)::in, list(module_name)::in, deps_map::in, 
 	io__state::di, io__state::uo) is det.
 generate_dependencies_write_d_files_2([], _, _TransOptOrder, _DepsMap) --> [].
-generate_dependencies_write_d_files_2([ModuleName | ModuleNames], TransDeps,
-		TransOptOrder, DepsMap) --> 
-	{ map__lookup(DepsMap, ModuleName, 
-		deps(_, Error, _IntDeps, ImplDeps, FactDeps)) },
+generate_dependencies_write_d_files_2([ModuleName | ModuleNames],
+		TransIntDeps, TransOptOrder, DepsMap) --> 
+	{ map__lookup(DepsMap, ModuleName, deps(_, ModuleImports0)) },
+	{ module_imports_get_error(ModuleImports0, Error) },
 	
-	{ FindModule = lambda([Module::in] is semidet, ( 
+	%
+	% Compute the trans-opt dependencies for this module.
+	% To avoid the possibility of cycles, each module is
+	% only allowed to depend on modules that occur later
+	% than it in the TransOptOrder.
+	%
+	{ FindModule = lambda([Module::in] is semidet, (
 		ModuleName \= Module )) },
 	{ list__takewhile(FindModule, TransOptOrder, _, TransOptDeps0) },
 	( { TransOptDeps0 = [ _ | TransOptDeps1 ] } ->
@@ -914,35 +1401,36 @@
 	;
 		{ TransOptDeps = [] }
 	),
+
+	%
 	% Note that even if a fatal error occured for one of the files that
 	% the current Module depends on, a .d file is still produced, even
 	% though it probably contains incorrect information.
 	( { Error \= fatal } ->
-		write_dependency_file(ModuleName, ImplDeps, TransDeps,
-			FactDeps, yes(TransOptDeps))
+		% Set the transitive interface dependencies for this module
+		{ module_imports_set_indirect_deps(ModuleImports0, TransIntDeps,
+			ModuleImports) },
+		write_dependency_file(ModuleImports, yes(TransOptDeps))
 	;
 		[]
 	),
-	generate_dependencies_write_d_files_2(ModuleNames, TransDeps,
+	generate_dependencies_write_d_files_2(ModuleNames, TransIntDeps,
 		TransOptOrder, DepsMap).
 
 % This is the data structure we use to record the dependencies.
 % We keep a map from module name to information about the module.
 
-:- type deps_map == map(string, deps).
+:- type deps_map == map(module_name, deps).
 :- type deps
 	---> deps(
-		bool,		% have we processed this module yet?
-		module_error,	% if we did, where there any errors?
-		list(string),	% interface dependencies
-		list(string),	% implementation dependencies
-		list(string)	% fact table dependencies
+		bool,			% have we processed this module yet?
+		module_imports
 	).
 
 	% (Module1 deps_rel Module2) means Module1 is imported by Module2.
-:- type deps_rel == relation(string).
+:- type deps_rel == relation(module_name).
 
-:- pred generate_deps_map(list(string), deps_map, deps_map,
+:- pred generate_deps_map(list(module_name), deps_map, deps_map,
 			io__state, io__state).
 :- mode generate_deps_map(in, in, out, di, uo) is det.
 
@@ -950,16 +1438,20 @@
 generate_deps_map([Module | Modules], DepsMap0, DepsMap) -->
 		% Look up the module's dependencies, and determine whether
 		% it has been processed yet.
-	lookup_dependencies(Module, DepsMap0, no, Done, Error, IntDeps, 
-				ImplDeps, FactDeps, DepsMap1),
+	lookup_dependencies(Module, DepsMap0, no, Done, ModuleImports,
+			DepsMap1),
 		% If the module hadn't been processed yet, then add its
-		% imports to the list of dependencies we need to generate
-		% and mark it as having been processed.
+		% imports, parents, and public children to the list of
+		% dependencies we need to generate, and mark it as
+		% having been processed.
 	( { Done = no } ->
-		{ map__set(DepsMap1, Module,
-			deps(yes, Error, IntDeps, ImplDeps, FactDeps), 
-				DepsMap2) },
-		{ list__append(ImplDeps, Modules, Modules1) }
+		{ map__set(DepsMap1, Module, deps(yes, ModuleImports),
+			DepsMap2) },
+		{ ModuleImports = module_imports(_,
+			ParentDeps, IntDeps, ImplDeps, _, InclDeps, _, _, _) },
+		{ list__condense(
+			[ParentDeps, IntDeps, ImplDeps, InclDeps, Modules],
+			Modules1) }
 	;
 		{ DepsMap2 = DepsMap1 },
 		{ Modules1 = Modules }
@@ -968,44 +1460,68 @@
 	generate_deps_map(Modules1, DepsMap2, DepsMap).
 
 
-	% Construct a dependency relation of all the modules in the program.
-:- pred deps_map_to_deps_rel(assoc_list(string, deps), deps_map,
-		deps_rel, deps_rel).
-:- mode deps_map_to_deps_rel(in, in, in, out) is det.
-
-deps_map_to_deps_rel([], _, Rel, Rel).
-deps_map_to_deps_rel([Module - Deps | DepsList], DepsMap, Rel0, Rel) :-
-	Deps = deps(_, ModuleError, IntDeps, ImplDeps, _),
+	% Construct a pair of dependency relations (the interface dependencies
+	% and the implementation dependencies) for all the modules in the
+	% program.
+:- pred deps_list_to_deps_rel(list(deps), deps_map,
+		deps_rel, deps_rel, deps_rel, deps_rel).
+:- mode deps_list_to_deps_rel(in, in, in, out, in, out) is det.
+
+deps_list_to_deps_rel([], _, IntRel, IntRel, ImplRel, ImplRel).
+deps_list_to_deps_rel([Deps | DepsList], DepsMap,
+		IntRel0, IntRel, ImplRel0, ImplRel) :-
+	Deps = deps(_, ModuleImports),
+	ModuleImports = module_imports(ModuleName,
+		ParentDeps, IntDeps, ImplDeps,
+		_IndirectDeps, PublicChildren, _FactDeps, _Items, ModuleError),
 	( ModuleError \= fatal ->
-		relation__add_element(Rel0, Module, ModuleRelKey, Rel1),
-		AddDeps =
-		    lambda([Dep::in, Relation0::in, Relation::out] is det, (
-			relation__add_element(Relation0, Dep,
-				DepRelKey, Relation1),
-			relation__add(Relation1, ModuleRelKey,
-				DepRelKey, Relation)
-		    )),
-		list__foldl(AddDeps, IntDeps, Rel1, Rel2),
-		list__foldl(AddDeps, ImplDeps, Rel2, Rel3)
+		% add interface dependencies to the interface deps relation
+		relation__add_element(IntRel0, ModuleName, IntModuleKey,
+			IntRel1),
+		AddIntDep = add_dep(IntModuleKey),
+		list__foldl(AddIntDep, ParentDeps, IntRel1, IntRel2),
+		list__foldl(AddIntDep, IntDeps, IntRel2, IntRel3),
+		list__foldl(AddIntDep, PublicChildren, IntRel3, IntRel4),
+
+		% add implementation dependencies to the impl. deps relation
+		% (the implementation dependencies are a superset of the
+		% interface dependencies)
+		relation__add_element(ImplRel0, ModuleName, ImplModuleKey,
+			ImplRel1),
+		AddImplDep = add_dep(ImplModuleKey),
+		list__foldl(AddImplDep, ParentDeps, ImplRel1, ImplRel2),
+		list__foldl(AddImplDep, IntDeps, ImplRel2, ImplRel3),
+		list__foldl(AddImplDep, PublicChildren, ImplRel3, ImplRel4),
+		list__foldl(AddImplDep, ImplDeps, ImplRel4, ImplRel5)
 	;
-		Rel3 = Rel0
+		IntRel4 = IntRel0,
+		ImplRel5 = ImplRel0
 	),
-	deps_map_to_deps_rel(DepsList, DepsMap, Rel3, Rel).
+	deps_list_to_deps_rel(DepsList, DepsMap,
+		IntRel4, IntRel, ImplRel5, ImplRel).
+
+:- pred add_dep(relation_key, T, relation(T), relation(T)).
+:- mode add_dep(in, in, in, out) is det.
+
+add_dep(ModuleRelKey, Dep, Relation0, Relation) :-
+	relation__add_element(Relation0, Dep, DepRelKey, Relation1),
+	relation__add(Relation1, ModuleRelKey, DepRelKey, Relation).
 
 %-----------------------------------------------------------------------------%
 	% Write out the `.dep' file, using the information collected in the
 	% deps_map data structure.
-:- pred generate_dependencies_write_dep_file(string::in, deps_map::in, 
+:- pred generate_dependencies_write_dep_file(module_name::in, deps_map::in, 
 	io__state::di, io__state::uo) is det.
-generate_dependencies_write_dep_file(Module, DepsMap) -->
+generate_dependencies_write_dep_file(ModuleName, DepsMap) -->
 	globals__io_lookup_bool_option(verbose, Verbose),
-	{ string__append(Module, ".dep", DepFileName) },
+	{ module_name_to_file_name(ModuleName, BaseFileName) },
+	{ string__append(BaseFileName, ".dep", DepFileName) },
 	maybe_write_string(Verbose, "% Creating auto-dependency file `"),
 	maybe_write_string(Verbose, DepFileName),
 	maybe_write_string(Verbose, "'...\n"),
 	io__open_output(DepFileName, DepResult),
 	( { DepResult = ok(DepStream) } ->
-		generate_dep_file(Module, DepsMap, DepStream),
+		generate_dep_file(ModuleName, DepsMap, DepStream),
 		io__close_output(DepStream),
 		maybe_write_string(Verbose, "% done.\n")
 	;
@@ -1015,14 +1531,16 @@
 	).
 
 
-:- pred generate_dep_file(string, deps_map, io__output_stream,
+:- pred generate_dep_file(module_name, deps_map, io__output_stream,
 			io__state, io__state).
 :- mode generate_dep_file(in, in, in, di, uo) is det.
 
 generate_dep_file(ModuleName, DepsMap, DepStream) -->
+	{ module_name_to_file_name(ModuleName, BaseFileName) },
 	io__write_string(DepStream,
 		"# Automatically generated dependencies for module `"),
-	io__write_string(DepStream, ModuleName),
+	{ prog_out__sym_name_to_string(ModuleName, ModuleNameString) },
+	io__write_string(DepStream, ModuleNameString),
 	io__write_string(DepStream, "'.\n"),
 	{ library__version(Version) },
 	io__write_string(DepStream,
@@ -1033,7 +1551,7 @@
 	{ map__keys(DepsMap, Modules0) },
 	{ select_ok_modules(Modules0, DepsMap, Modules) },
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".ms ="),
 	write_dependencies_list(Modules, ".m", DepStream),
 	io__write_string(DepStream, "\n\n"),
@@ -1041,7 +1559,7 @@
 	globals__io_lookup_bool_option(assume_gmake, Gmake),
 	(
 		{ Gmake = yes },
-		{ string__append(ModuleName, ".ms", VarName) },
+		{ string__append(BaseFileName, ".ms", VarName) },
 		{ Basis = yes(VarName - ".m") }
 	;
 		{ Gmake = no },
@@ -1050,316 +1568,332 @@
 
 	{ get_extra_link_objects(Modules, DepsMap, ExtraLinkObjs) },
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".nos = "),
 	write_compact_dependencies_list(Modules, ".no", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".qls = "),
 	write_compact_dependencies_list(Modules, ".ql", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".cs = "),
 	write_compact_dependencies_list(Modules, ".c", Basis, DepStream),
-	write_dependencies_list(ExtraLinkObjs, ".c", DepStream),
+	write_file_dependencies_list(ExtraLinkObjs, ".c", DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".os = "),
 	write_compact_dependencies_list(Modules, ".o", Basis, DepStream),
-	write_dependencies_list(ExtraLinkObjs, ".o", DepStream),
+	write_file_dependencies_list(ExtraLinkObjs, ".o", DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".pic_os = "),
 	write_compact_dependencies_list(Modules, ".$(EXT_FOR_PIC_OBJECTS)",
 		Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".dirs = "),
 	write_compact_dependencies_list(Modules, ".dir", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".dir_os = "),
 	write_compact_dependencies_list(Modules, ".dir/*.o", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".ss = "),
 	write_compact_dependencies_list(Modules, ".s", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".errs = "),
 	write_compact_dependencies_list(Modules, ".err", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".dates = "),
 	write_compact_dependencies_list(Modules, ".date", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
+	io__write_string(DepStream, ".date0s = "),
+	write_compact_dependencies_list(Modules, ".date0", Basis, DepStream),
+	io__write_string(DepStream, "\n"),
+
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".date3s = "),
 	write_compact_dependencies_list(Modules, ".date3", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".optdates = "),
 	write_compact_dependencies_list(Modules, ".optdate", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".trans_opt_dates = "),
 	write_compact_dependencies_list(Modules, ".trans_opt_date", Basis,
 								DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".ds = "),
 	write_compact_dependencies_list(Modules, ".d", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".hs = "),
 	write_compact_dependencies_list(Modules, ".h", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".ints = "),
 	write_compact_dependencies_list(Modules, ".int", Basis, DepStream),
 	write_compact_dependencies_separator(Basis, DepStream),
 	write_compact_dependencies_list(Modules, ".int2", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
+	io__write_string(DepStream, ".int0s = "),
+	write_compact_dependencies_list(Modules, ".int0", Basis, DepStream),
+	io__write_string(DepStream, "\n"),
+
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".int3s = "),
 	write_compact_dependencies_list(Modules, ".int3", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".opts = "),
 	write_compact_dependencies_list(Modules, ".opt", Basis, DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".trans_opts = "),
 	write_compact_dependencies_list(Modules, ".trans_opt", Basis,
 								DepStream),
 	io__write_string(DepStream, "\n"),
 
-	io__write_string(DepStream, ModuleName),
+	io__write_string(DepStream, BaseFileName),
 	io__write_string(DepStream, ".profs = "),
 	write_compact_dependencies_list(Modules, ".prof", Basis, DepStream),
 	io__write_string(DepStream, "\n\n"),
 
 	io__write_strings(DepStream, [
-		ModuleName, " : $(", ModuleName, ".os) ",
-		ModuleName, "_init.o $(MLOBJS)\n",
-		"\t$(ML) $(GRADEFLAGS) $(MLFLAGS) -o ", ModuleName, " ",
-		ModuleName, "_init.o \\\n",
-		"\t	$(", ModuleName, ".os) $(MLOBJS) $(MLLIBS)\n\n"
+		BaseFileName, " : $(", BaseFileName, ".os) ",
+		BaseFileName, "_init.o $(MLOBJS)\n",
+		"\t$(ML) $(GRADEFLAGS) $(MLFLAGS) -o ", BaseFileName, " ",
+		BaseFileName, "_init.o \\\n",
+		"\t	$(", BaseFileName, ".os) $(MLOBJS) $(MLLIBS)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".split : ", ModuleName, ".split.a ",
-				ModuleName, "_init.o\n",
-		"\t$(ML) $(GRADEFLAGS) $(MLFLAGS) -o ", ModuleName, ".split ",
-			ModuleName, "_init.o \\\n",
-		"\t	", ModuleName, ".split.a $(MLLIBS)\n\n"
+		BaseFileName, ".split : ", BaseFileName, ".split.a ",
+				BaseFileName, "_init.o\n",
+		"\t$(ML) $(GRADEFLAGS) $(MLFLAGS) -o ", BaseFileName, ".split ",
+			BaseFileName, "_init.o \\\n",
+		"\t	", BaseFileName, ".split.a $(MLLIBS)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".split.a : $(", ModuleName, ".dir_os) ",
+		BaseFileName, ".split.a : $(", BaseFileName, ".dir_os) ",
 				"$(MLOBJS)\n",
-		"\trm -f ", ModuleName, ".split.a\n",
-		"\t$(AR) $(ARFLAGS) ", ModuleName, ".split.a $(MLOBJS)\n",
-		"\tfor dir in $(", ModuleName, ".dirs); do \\\n",
-		"\t	$(AR) q ", ModuleName, ".split.a $$dir/*.o; \\\n",
+		"\trm -f ", BaseFileName, ".split.a\n",
+		"\t$(AR) $(ARFLAGS) ", BaseFileName, ".split.a $(MLOBJS)\n",
+		"\tfor dir in $(", BaseFileName, ".dirs); do \\\n",
+		"\t	$(AR) q ", BaseFileName, ".split.a $$dir/*.o; \\\n",
 		"\tdone\n",
-		"\t$(RANLIB) $(RANLIBFLAGS) ", ModuleName, ".split.a\n\n"
+		"\t$(RANLIB) $(RANLIBFLAGS) ", BaseFileName, ".split.a\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		"lib", ModuleName, " : ",
-		"lib", ModuleName, ".a ",
-		"lib", ModuleName, ".$(EXT_FOR_SHARED_LIB) \\\n",
-		"\t\t$(", ModuleName, ".ints) ",
-		"$(", ModuleName, ".opts) ",
-		ModuleName, ".init\n\n"
+		"lib", BaseFileName, " : ",
+		"lib", BaseFileName, ".a ",
+		"lib", BaseFileName, ".$(EXT_FOR_SHARED_LIB) \\\n",
+		"\t\t$(", BaseFileName, ".ints) ",
+		"$(", BaseFileName, ".int3s) ",
+		"$(", BaseFileName, ".opts) ",
+		BaseFileName, ".init\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		"lib", ModuleName, ".so : $(", ModuleName, ".pic_os) ",
+		"lib", BaseFileName, ".so : $(", BaseFileName, ".pic_os) ",
 				"$(MLPICOBJS)\n",
 		"\t$(ML) --make-shared-lib $(GRADEFLAGS) $(MLFLAGS) -o ",
-			"lib", ModuleName, ".so \\\n",
-		"\t\t$(", ModuleName, ".pic_os) $(MLPICOBJS) $(MLLIBS)\n\n"
+			"lib", BaseFileName, ".so \\\n",
+		"\t\t$(", BaseFileName, ".pic_os) $(MLPICOBJS) $(MLLIBS)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		"lib", ModuleName, ".a : $(", ModuleName, ".os) $(MLOBJS)\n",
-		"\trm -f ", ModuleName, ".a\n",
-		"\t$(AR) $(ARFLAGS) lib", ModuleName, ".a ",
-			"$(", ModuleName, ".os) $(MLOBJS)\n",
-		"\t$(RANLIB) $(RANLIBFLAGS) lib", ModuleName, ".a\n\n"
+		"lib", BaseFileName, ".a : $(", BaseFileName,
+				".os) $(MLOBJS)\n",
+		"\trm -f ", BaseFileName, ".a\n",
+		"\t$(AR) $(ARFLAGS) lib", BaseFileName, ".a ",
+			"$(", BaseFileName, ".os) $(MLOBJS)\n",
+		"\t$(RANLIB) $(RANLIBFLAGS) lib", BaseFileName, ".a\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".init : ", ModuleName, ".dep\n",
-		"\tfor file in $(", ModuleName, ".ms); do \\\n",
+		BaseFileName, ".init : ", BaseFileName, ".dep\n",
+		"\tfor file in $(", BaseFileName, ".ms); do \\\n",
 		"\t\techo ""INIT mercury__`basename $$file .m`__init""; \\\n",
-		"\tdone > ", ModuleName, ".init\n\n"
+		"\tdone > ", BaseFileName, ".init\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, "_init.c :\n",
-		"\t$(C2INIT) $(C2INITFLAGS) $(", ModuleName, ".ms) > ",
-			ModuleName, "_init.c\n\n"
+		BaseFileName, "_init.c :\n",
+		"\t$(C2INIT) $(C2INITFLAGS) $(", BaseFileName, ".ms) > ",
+			BaseFileName, "_init.c\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".nu : $(", ModuleName, ".nos)\n",
-		"\t$(MNL) $(MNLFLAGS) -o ", ModuleName, ".nu ",
-			"$(", ModuleName, ".nos)\n\n",
-
-		ModuleName, ".nu.debug : $(", ModuleName, ".nos)\n",
-		"\t$(MNL) --debug $(MNLFLAGS) -o ", ModuleName, ".nu.debug ",
-			"$(", ModuleName, ".nos)\n\n"
+		BaseFileName, ".nu : $(", BaseFileName, ".nos)\n",
+		"\t$(MNL) $(MNLFLAGS) -o ", BaseFileName, ".nu ",
+			"$(", BaseFileName, ".nos)\n\n",
+
+		BaseFileName, ".nu.debug : $(", BaseFileName, ".nos)\n",
+		"\t$(MNL) --debug $(MNLFLAGS) -o ", BaseFileName, ".nu.debug ",
+			"$(", BaseFileName, ".nos)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".sicstus : $(", ModuleName, ".qls)\n",
-		"\t$(MSL) $(MSLFLAGS) -o ", ModuleName, ".sicstus ",
-			"$(", ModuleName, ".qls)\n\n",
-
-		ModuleName, ".sicstus.debug : $(", ModuleName, ".qls)\n",
-			"\t$(MSL) --debug $(MSLFLAGS) -o ", ModuleName,
-			".sicstus.debug $(", ModuleName, ".qls)\n\n"
+		BaseFileName, ".sicstus : $(", BaseFileName, ".qls)\n",
+		"\t$(MSL) $(MSLFLAGS) -o ", BaseFileName, ".sicstus ",
+			"$(", BaseFileName, ".qls)\n\n",
+
+		BaseFileName, ".sicstus.debug : $(", BaseFileName, ".qls)\n",
+			"\t$(MSL) --debug $(MSLFLAGS) -o ", BaseFileName,
+			".sicstus.debug $(", BaseFileName, ".qls)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".check : $(", ModuleName, ".errs)\n\n",
+		BaseFileName, ".check : $(", BaseFileName, ".errs)\n\n",
 
-		ModuleName, ".ints : $(", ModuleName, ".dates)\n\n",
-		ModuleName, ".int3s : $(", ModuleName, ".date3s)\n\n",
-		ModuleName, ".opts : $(", ModuleName, ".optdates)\n\n"
+		BaseFileName, ".ints : $(", BaseFileName, ".dates)\n\n",
+		BaseFileName, ".int3s : $(", BaseFileName, ".date3s)\n\n",
+		BaseFileName, ".opts : $(", BaseFileName, ".optdates)\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		"clean : ", ModuleName, ".clean\n"
+		"clean : ", BaseFileName, ".clean\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".clean :\n",
-		"\t-rm -rf ", ModuleName, ".dir\n",
-		"\t-rm -f $(", ModuleName, ".cs) ", ModuleName, "_init.c\n",
-		"\t-rm -f $(", ModuleName, ".ss) ", ModuleName, "_init.s\n",
-		"\t-rm -f $(", ModuleName, ".os) ", ModuleName, "_init.o\n",
-		"\t-rm -f $(", ModuleName, ".pic_os) ",
-						ModuleName, "_init.pic_o\n",
-		"\t-rm -f $(", ModuleName, ".trans_opt_dates)\n",
-		"\t-rm -f $(", ModuleName, ".trans_opts)\n",
-		"\t-rm -f $(", ModuleName, ".profs)\n",
-		"\t-rm -f $(", ModuleName, ".nos)\n",
-		"\t-rm -f $(", ModuleName, ".qls)\n",
-		"\t-rm -f $(", ModuleName, ".errs)\n"
+		BaseFileName, ".clean :\n",
+		"\t-rm -rf ", BaseFileName, ".dir\n",
+		"\t-rm -f $(", BaseFileName, ".cs) ", BaseFileName, "_init.c\n",
+		"\t-rm -f $(", BaseFileName, ".ss) ", BaseFileName, "_init.s\n",
+		"\t-rm -f $(", BaseFileName, ".os) ", BaseFileName, "_init.o\n",
+		"\t-rm -f $(", BaseFileName, ".pic_os) ",
+						BaseFileName, "_init.pic_o\n",
+		"\t-rm -f $(", BaseFileName, ".trans_opt_dates)\n",
+		"\t-rm -f $(", BaseFileName, ".trans_opts)\n",
+		"\t-rm -f $(", BaseFileName, ".profs)\n",
+		"\t-rm -f $(", BaseFileName, ".nos)\n",
+		"\t-rm -f $(", BaseFileName, ".qls)\n",
+		"\t-rm -f $(", BaseFileName, ".errs)\n"
 	]),
 
 	io__write_string(DepStream, "\n"),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".change_clean :\n",
-		"\t-rm -f $(", ModuleName, ".cs) ", ModuleName, "_init.c\n",
-		"\t-rm -f $(", ModuleName, ".ss) ", ModuleName, "_init.s\n",
-		"\t-rm -f $(", ModuleName, ".os) ", ModuleName, "_init.o\n",
-		"\t-rm -f $(", ModuleName, ".hs)\n",
-		"\t-rm -f $(", ModuleName, ".ds)\n",
+		BaseFileName, ".change_clean :\n",
+		"\t-rm -f $(", BaseFileName, ".cs) ", BaseFileName, "_init.c\n",
+		"\t-rm -f $(", BaseFileName, ".ss) ", BaseFileName, "_init.s\n",
+		"\t-rm -f $(", BaseFileName, ".os) ", BaseFileName, "_init.o\n",
+		"\t-rm -f $(", BaseFileName, ".hs)\n",
+		"\t-rm -f $(", BaseFileName, ".ds)\n",
 		"\t-rm -f ",
-			ModuleName, " ",
-			ModuleName, ".split ",
-			ModuleName, ".split.a ",
-			ModuleName, ".init ",
-			"lib", ModuleName, ".a ",
-			"lib", ModuleName, ".so ",
-			ModuleName, ".dep\n\n"
+			BaseFileName, " ",
+			BaseFileName, ".split ",
+			BaseFileName, ".split.a ",
+			BaseFileName, ".init ",
+			"lib", BaseFileName, ".a ",
+			"lib", BaseFileName, ".so ",
+			BaseFileName, ".dep\n\n"
 	]),
 
 	io__write_strings(DepStream, [
-		"realclean : ", ModuleName, ".realclean\n"
+		"realclean : ", BaseFileName, ".realclean\n"
 	]),
 
 	io__write_strings(DepStream, [
-		ModuleName, ".realclean : ", ModuleName, ".clean\n",
-		"\t-rm -f $(", ModuleName, ".dates)\n",
-		"\t-rm -f $(", ModuleName, ".date3s)\n",
-		"\t-rm -f $(", ModuleName, ".optdates)\n",
-		"\t-rm -f $(", ModuleName, ".ints)\n",
-		"\t-rm -f $(", ModuleName, ".int3s)\n",
-		"\t-rm -f $(", ModuleName, ".opts)\n",
-		"\t-rm -f $(", ModuleName, ".ds)\n",
-		"\t-rm -f $(", ModuleName, ".hs)\n"
+		BaseFileName, ".realclean : ", BaseFileName, ".clean\n",
+		"\t-rm -f $(", BaseFileName, ".dates)\n",
+		"\t-rm -f $(", BaseFileName, ".date0s)\n",
+		"\t-rm -f $(", BaseFileName, ".date3s)\n",
+		"\t-rm -f $(", BaseFileName, ".optdates)\n",
+		"\t-rm -f $(", BaseFileName, ".ints)\n",
+		"\t-rm -f $(", BaseFileName, ".int0s)\n",
+		"\t-rm -f $(", BaseFileName, ".int3s)\n",
+		"\t-rm -f $(", BaseFileName, ".opts)\n",
+		"\t-rm -f $(", BaseFileName, ".ds)\n",
+		"\t-rm -f $(", BaseFileName, ".hs)\n"
 	]),
 	io__write_strings(DepStream, [
 		"\t-rm -f ",
-			ModuleName, " ",
-			ModuleName, ".split ",
-			ModuleName, ".split.a ",
-			ModuleName, ".init ",
-			"lib", ModuleName, ".a ",
-			"lib", ModuleName, ".so ",
-			ModuleName, ".nu ",
-			ModuleName, ".nu.save ",
-			ModuleName, ".nu.debug.save ",
-			ModuleName, ".nu.debug ",
-			ModuleName, ".sicstus ",
-			ModuleName, ".sicstus.debug ",
-			ModuleName, ".dep\n\n"
+			BaseFileName, " ",
+			BaseFileName, ".split ",
+			BaseFileName, ".split.a ",
+			BaseFileName, ".init ",
+			"lib", BaseFileName, ".a ",
+			"lib", BaseFileName, ".so ",
+			BaseFileName, ".nu ",
+			BaseFileName, ".nu.save ",
+			BaseFileName, ".nu.debug.save ",
+			BaseFileName, ".nu.debug ",
+			BaseFileName, ".sicstus ",
+			BaseFileName, ".sicstus.debug ",
+			BaseFileName, ".dep\n\n"
 	]),
 	io__write_strings(DepStream, [
-		"clean_nu : ", ModuleName, ".clean_nu\n",
-		ModuleName, ".clean_nu :\n",
-		"\t-rm -f $(", ModuleName, ".nos)\n\n",
-
-		"clean_sicstus : ", ModuleName, ".clean_sicstus\n",
-		ModuleName, ".clean_sicstus :\n",
-		"\t-rm -f $(", ModuleName, ".qls)\n\n"
+		"clean_nu : ", BaseFileName, ".clean_nu\n",
+		BaseFileName, ".clean_nu :\n",
+		"\t-rm -f $(", BaseFileName, ".nos)\n\n",
+
+		"clean_sicstus : ", BaseFileName, ".clean_sicstus\n",
+		BaseFileName, ".clean_sicstus :\n",
+		"\t-rm -f $(", BaseFileName, ".qls)\n\n"
 	]).
 
 %-----------------------------------------------------------------------------%
 	% get_extra_link_objects(Modules, DepsMap, ExtraLinkObjs) },
 	% Find any extra .o files that should be linked into the executable.
 	% Currently only looks for fact table object files.
-:- pred get_extra_link_objects(list(string), deps_map, list(string)).
+:- pred get_extra_link_objects(list(module_name), deps_map, list(string)).
 :- mode get_extra_link_objects(in, in, out) is det.
 
 get_extra_link_objects(Modules, DepsMap, ExtraLinkObjs) :-
 	get_extra_link_objects_2(Modules, DepsMap, [], ExtraLinkObjs).
 
-:- pred get_extra_link_objects_2(list(string), deps_map, 
+:- pred get_extra_link_objects_2(list(module_name), deps_map, 
 		list(string), list(string)).
 :- mode get_extra_link_objects_2(in, in, in, out) is det.
 
 get_extra_link_objects_2([], _DepsMap, ExtraLinkObjs, ExtraLinkObjs).
 get_extra_link_objects_2([Module | Modules], DepsMap, 
 		ExtraLinkObjs0, ExtraLinkObjs) :-
-	map__lookup(DepsMap, Module, deps(_, _, _, _, ObjList)),
-	list__append(ObjList, ExtraLinkObjs0, ExtraLinkObjs1),
+	map__lookup(DepsMap, Module, deps(_, ModuleImports)),
+	ModuleImports = module_imports(_, _, _, _, _, _, FactDeps, _, _),
+	list__append(FactDeps, ExtraLinkObjs0, ExtraLinkObjs1),
 	get_extra_link_objects_2(Modules, DepsMap, ExtraLinkObjs1, 
 		ExtraLinkObjs).
 
 %-----------------------------------------------------------------------------%
 
-:- pred select_ok_modules(list(string), deps_map, list(string)).
+:- pred select_ok_modules(list(module_name), deps_map, list(module_name)).
 :- mode select_ok_modules(in, in, out) is det.
 
 select_ok_modules([], _, []).
 select_ok_modules([Module | Modules0], DepsMap, Modules) :-
-	map__lookup(DepsMap, Module, deps(_, Error, _, _, _)),
+	map__lookup(DepsMap, Module, deps(_, ModuleImports)),
+	module_imports_get_error(ModuleImports, Error),
 	( Error = fatal ->
 		Modules = Modules1
 	;
@@ -1369,20 +1903,28 @@
 
 %-----------------------------------------------------------------------------%
 
-:- pred write_dependencies_list(list(string), string, io__output_stream,
+:- pred write_dependencies_list(list(module_name), string, io__output_stream,
 				io__state, io__state).
 :- mode write_dependencies_list(in, in, in, di, uo) is det.
 
-write_dependencies_list([], _, _) --> [].
-write_dependencies_list([Module | Modules], Suffix, DepStream) -->
+write_dependencies_list(Modules, Suffix, DepStream) -->
+	{ list__map(module_name_to_file_name, Modules, FileNames) },
+	write_file_dependencies_list(FileNames, Suffix, DepStream).
+
+:- pred write_file_dependencies_list(list(string), string, io__output_stream,
+				io__state, io__state).
+:- mode write_file_dependencies_list(in, in, in, di, uo) is det.
+
+write_file_dependencies_list([], _, _) --> [].
+write_file_dependencies_list([FileName | FileNames], Suffix, DepStream) -->
 	io__write_string(DepStream, " \\\n\t"),
-	io__write_string(DepStream, Module),
+	io__write_string(DepStream, FileName),
 	io__write_string(DepStream, Suffix),
-	write_dependencies_list(Modules, Suffix, DepStream).
+	write_file_dependencies_list(FileNames, Suffix, DepStream).
 
 %-----------------------------------------------------------------------------%
 
-:- pred write_compact_dependencies_list(list(string), string,
+:- pred write_compact_dependencies_list(list(module_name), string,
 	maybe(pair(string)), io__output_stream, io__state, io__state).
 :- mode write_compact_dependencies_list(in, in, in, in, di, uo) is det.
 
@@ -1412,65 +1954,73 @@
 	% If we don't know its dependencies, read the
 	% module and save the dependencies in the dependency map.
 
-:- pred lookup_dependencies(string, deps_map, bool,
-		bool, module_error, list(string), list(string), list(string),
-		deps_map, io__state, io__state).
-:- mode lookup_dependencies(in, in, in, out, out, out, out, out, out, 
-		di, uo) is det.
+:- pred lookup_dependencies(module_name, deps_map, bool, bool,
+		module_imports, deps_map, io__state, io__state).
+:- mode lookup_dependencies(in, in, in, out, out, out, di, uo) is det.
 
-lookup_dependencies(Module, DepsMap0, Search, Done, Error, IntDeps, 
-		ImplDeps, FactDeps, DepsMap) -->
+lookup_dependencies(Module, DepsMap0, Search, Done, ModuleImports, DepsMap) -->
 	(
 		{ map__search(DepsMap0, Module,
-			deps(Done0, Error0, IntDeps0, ImplDeps0, FactDeps0)) }
+			deps(Done0, ModuleImports0)) }
 	->
 		{ Done = Done0 },
-		{ Error = Error0 },
-		{ IntDeps = IntDeps0 },
-		{ ImplDeps = ImplDeps0 },
-		{ FactDeps = FactDeps0 },
+		{ ModuleImports0 = ModuleImports },
 		{ DepsMap = DepsMap0 }
 	;
-		read_dependencies(Module, Search, IntDeps, ImplDeps, FactDeps, 
-			Error),
-		{ map__det_insert(DepsMap0, Module, 
-		    deps(no, Error, IntDeps, ImplDeps, FactDeps), DepsMap) },
+		read_dependencies(Module, Search, ModuleImports),
+		{ map__det_insert(DepsMap0, Module, deps(no, ModuleImports),
+			DepsMap) },
 		{ Done = no }
 	).
 
-	% Read a module to determine its dependencies.
+	% Read a module to determine its (direct) dependencies
+
+:- pred read_dependencies(module_name, bool, module_imports,
+			io__state, io__state).
+:- mode read_dependencies(in, in, out, di, uo) is det.
 
-:- pred read_dependencies(string, bool, list(string), list(string),
-			list(string), module_error, io__state, io__state).
-:- mode read_dependencies(in, in, out, out, out, out, di, uo) is det.
-
-read_dependencies(Module, Search, InterfaceDeps, ImplementationDeps, 
-		FactTableDeps, Error) -->
-	read_mod_ignore_errors(Module, ".m",
+read_dependencies(ModuleName, Search, ModuleImports) -->
+	read_mod_ignore_errors(ModuleName, ".m",
 		"Getting dependencies for module", Search, Items0, Error),
 	( { Items0 = [], Error = fatal } ->
-		read_mod_ignore_errors(Module, ".int", 
+		read_mod_ignore_errors(ModuleName, ".int", 
 		    "Getting dependencies for module interface", Search, 
 		    Items, _Error)
 	;
 		{ Items = Items0 }
 	),
-	{ get_dependencies(Items, ImplImportDeps, ImplUseDeps) },
-	{ list__append(ImplImportDeps, ImplUseDeps, ImplementationDeps0) },
+
+	{ get_ancestors(ModuleName, ParentDeps) },
+
+	{ get_dependencies(Items, ImplImportDeps0, ImplUseDeps0) },
+	{ add_implicit_imports(ImplImportDeps0, ImplUseDeps0,
+		ImplImportDeps, ImplUseDeps) },
+	{ list__append(ImplImportDeps, ImplUseDeps, ImplementationDeps) },
+
 	{ get_interface(Items, no, InterfaceItems) },
-	{ get_dependencies(InterfaceItems, InterfaceImportDeps,
-		InterfaceUseDeps) },
+	{ get_dependencies(InterfaceItems, InterfaceImportDeps0,
+		InterfaceUseDeps0) },
+	{ add_implicit_imports(InterfaceImportDeps0, InterfaceUseDeps0,
+		InterfaceImportDeps, InterfaceUseDeps) },
 	{ list__append(InterfaceImportDeps, InterfaceUseDeps, 
-		InterfaceDeps0) },
-	{ InterfaceDeps = ["mercury_builtin" | InterfaceDeps0] },
-	{ ImplementationDeps = ["mercury_builtin" | ImplementationDeps0] },
-	{ get_fact_table_dependencies(Items, FactTableDeps) }.
+		InterfaceDeps) },
+
+	% we don't fill in the indirect dependencies yet
+	{ IndirectDeps = [] },
+
+	{ get_children(InterfaceItems, IncludeDeps) },
+
+	{ get_fact_table_dependencies(Items, FactTableDeps) },
+
+	{ ModuleImports = module_imports(ModuleName, ParentDeps, InterfaceDeps,
+		ImplementationDeps, IndirectDeps, IncludeDeps, FactTableDeps,
+		[], Error) }.
 
 %-----------------------------------------------------------------------------%
 
 read_mod(ModuleName, Extension, Descr, Search, Items, Error) -->
-	{ dir__basename(ModuleName, Module) },
-	{ string__append(ModuleName, Extension, FileName) },
+	{ module_name_to_file_name(ModuleName, BaseFileName) },
+	{ string__append(BaseFileName, Extension, FileName) },
 	globals__io_lookup_bool_option(very_verbose, VeryVerbose),
 	maybe_write_string(VeryVerbose, "% "),
 	maybe_write_string(VeryVerbose, Descr),
@@ -1478,7 +2028,8 @@
 	maybe_write_string(VeryVerbose, FileName),
 	maybe_write_string(VeryVerbose, "'... "),
 	maybe_flush_output(VeryVerbose),
-	prog_io__read_module(FileName, Module, Search, Error, Messages, Items),
+	prog_io__read_module(FileName, ModuleName, Search,
+		Error, Messages, Items),
 	( { Error = fatal } ->
 		maybe_write_string(VeryVerbose, "fatal error(s).\n"),
 		io__set_exit_status(1)
@@ -1502,190 +2053,270 @@
 */
 
 read_mod_ignore_errors(ModuleName, Extension, Descr, Search, Items, Error) -->
-	{ dir__basename(ModuleName, Module) },
+	{ module_name_to_file_name(ModuleName, BaseFileName) },
+	{ string__append(BaseFileName, Extension, FileName) },
 	globals__io_lookup_bool_option(very_verbose, VeryVerbose),
 	maybe_write_string(VeryVerbose, "% "),
 	maybe_write_string(VeryVerbose, Descr),
 	maybe_write_string(VeryVerbose, " `"),
-	maybe_write_string(VeryVerbose, Module),
+	maybe_write_string(VeryVerbose, FileName),
 	maybe_write_string(VeryVerbose, "'... "),
 	maybe_flush_output(VeryVerbose),
-	{ string__append(ModuleName, Extension, FileName) },
-	prog_io__read_module(FileName, Module, Search, Error, _Messages, Items),
+	prog_io__read_module(FileName, ModuleName, Search,
+		Error, _Messages, Items),
 	maybe_write_string(VeryVerbose, "done.\n").
 
-:- pred read_mod_short_interface(string, string, string, bool, item_list, 
-		module_error, io__state, io__state).
-:- mode read_mod_short_interface(in, in, in, in, out, out, di, uo) is det.
-read_mod_short_interface(Module, Ext, Descr, Search, Items, Error) -->
-	read_mod(Module, Ext, Descr, Search, Items, Error).
+%-----------------------------------------------------------------------------%
 
-:- pred read_mod_interface(string, string, bool, item_list, module_error,
-				io__state, io__state).
-:- mode read_mod_interface(in, in, in, out, out, di, uo) is det.
+	% process_module_private_interfaces(Ancestors, DirectImports0,
+	%			DirectImports, DirectUses0, DirectUses,
+	%			Module0, Module):
+	%  	Read the complete private interfaces for modules in Ancestors,
+	%	and append any imports/uses in the ancestors to the
+	%	corresponding previous lists.
+
+:- pred process_module_private_interfaces(list(module_name),
+		list(module_name), list(module_name),
+		list(module_name), list(module_name),
+		module_imports, module_imports, io__state, io__state).
+:- mode process_module_private_interfaces(in, in, out, in, out, in, out,
+		di, uo) is det.
 
-read_mod_interface(Module, Descr, Search, Items, Error) -->
-	read_mod(Module, ".int", Descr, Search, Items, Error).
+process_module_private_interfaces([], DirectImports, DirectImports,
+		DirectUses, DirectUses, Module, Module) --> [].
+process_module_private_interfaces([Ancestor | Ancestors],
+		DirectImports0, DirectImports, DirectUses0, DirectUses,
+		Module0, Module) -->
+	{ Module0 = module_imports(ModuleName, ModAncestors0,
+				ModInterfaceDeps, ModImplementationDeps,
+				ModIndirectDeps, ModPublicChildren,
+				ModFactDeps, ModItems0, ModError0) },
+	(
+		{ Ancestor = ModuleName }
+	->
+		{ error("modules.m: module is its own ancestor?") }
+	;
+		{ list__member(Ancestor, ModAncestors0) }
+	->
+		% we've already read it
+		process_module_private_interfaces(Ancestors,
+				DirectImports0, DirectImports,
+				DirectUses0, DirectUses,
+				Module0, Module)
+	;
+		read_mod(Ancestor, ".int0",
+			"Reading private interface for module", yes, 
+			PrivateIntItems, PrivateIntError),
+		{ strip_off_interface_decl(PrivateIntItems, Items) },
+		{ maybe_add_int_error(PrivateIntError, ModError0, ModError) },
 
-%-----------------------------------------------------------------------------%
+		globals__io_lookup_bool_option(statistics, Statistics),
+		maybe_report_stats(Statistics),
 
-process_module_interfaces(Imports, IndirectImports0, Module0, Module) -->
-	process_module_interfaces_2(Imports, IndirectImports0,
-		IndirectImports, Module0, Module1),
-	process_module_short_interfaces(IndirectImports, Module1, Module).
+		( { PrivateIntError = fatal } ->
+			{ ModAncestors = ModAncestors0 }
+		;
+			{ ModAncestors = [Ancestor | ModAncestors0] }
+		),
+		{ get_dependencies(Items, AncDirectImports, AncDirectUses) },
+		{ list__append(DirectImports0, AncDirectImports,
+				DirectImports1) },
+		{ list__append(DirectUses0, AncDirectUses, DirectUses1) },
+		{ list__append(ModItems0, Items, ModItems) },
+		{ Module1 = module_imports(ModuleName, ModAncestors,
+				ModInterfaceDeps, ModImplementationDeps,
+				ModIndirectDeps, ModPublicChildren,
+				ModFactDeps, ModItems, ModError) },
+		process_module_private_interfaces(Ancestors, DirectImports1,
+				DirectImports, DirectUses1, DirectUses,
+				Module1, Module)
+	).
 
-:- pred process_module_interfaces_2(list(string), list(string), 
-	list(string), module_imports, module_imports, io__state, io__state).
-:- mode process_module_interfaces_2(in, in, out, in, out, di, uo) is det.
+%-----------------------------------------------------------------------------%
 
-process_module_interfaces_2([], IndirectImports, IndirectImports, 
+process_module_long_interfaces([], _Ext, IndirectImports, IndirectImports, 
 		Module, Module) --> [].
-process_module_interfaces_2([Import | Imports], IndirectImports0,
+process_module_long_interfaces([Import | Imports], Ext, IndirectImports0,
 		IndirectImports, Module0, Module) -->
-	{ Module0 = module_imports(ModuleName, DirectImports0,
-				OldIndirectImports, Items0, Error0) },
+	{ Module0 = module_imports(ModuleName, ModAncestors,
+				ModInterfaceImports, ModImplementationImports0,
+				ModIndirectImports, ModPublicChildren,
+				ModFactDeps, ModItems0, ModError0) },
 	(
-		{ Import = ModuleName }
-	->
-		( { ModuleName = "mercury_builtin" } ->
-			[]
-		;
-			globals__io_lookup_bool_option(warn_simple_code,
-							Warn),
-			( { Warn = yes } ->
-				{ term__context_init(ModuleName, 1, Context) },
-				prog_out__write_context(Context),
-				io__write_string(
-					"Warning: module imports itself!\n")
-			;
-				[]
-			)
-		),
-		process_module_interfaces_2(Imports, IndirectImports0,
-				IndirectImports, Module0, Module)
-	;
-		{ list__member(Import, DirectImports0) }
+		% have we already read it?
+		( { Import = ModuleName }
+		; { list__member(Import, ModAncestors) }
+		; { list__member(Import, ModInterfaceImports) }
+		; { list__member(Import, ModImplementationImports0) }
+		)
 	->
-		process_module_interfaces_2(Imports, IndirectImports0,
-				IndirectImports, Module0, Module)
+		process_module_long_interfaces(Imports, Ext,
+				IndirectImports0, IndirectImports,
+				Module0, Module)
 	;
-		read_mod_interface(Import,
+		read_mod(Import, Ext,
 			"Reading interface for module", yes, 
-			LongIntItems1, Error1),
-		% strip off the `:- interface' declaration at the start, if any
-		{
-			LongIntItems1 = [ FirstItem | LongIntItems2 ],
-			FirstItem = module_defn(_, interface) - _
-		->
-			Items1 = LongIntItems2
-		;
-			Items1 = LongIntItems1
-		},
-		{ ( Error1 \= no ->
-			Error2 = yes
-		;
-			Error2 = Error0
-		) },
+			LongIntItems, LongIntError),
+		{ strip_off_interface_decl(LongIntItems, Items) },
+		{ maybe_add_int_error(LongIntError, ModError0, ModError) },
 
 		globals__io_lookup_bool_option(statistics, Statistics),
 		maybe_report_stats(Statistics),
 
-		{ get_dependencies(Items1, IndirectImports1, IndirectUses1) },
-		( { Error1 = fatal } ->
-			{ DirectImports1 = DirectImports0 }
+		( { LongIntError = fatal } ->
+			{ ModImplementationImports = ModImplementationImports0 }
 		;
-			{ DirectImports1 = [Import | DirectImports0] }
+			{ ModImplementationImports =
+				[Import | ModImplementationImports0] }
 		),
+		{ get_dependencies(Items, IndirectImports1, IndirectUses1) },
 		{ list__append(IndirectImports0, IndirectImports1,
 			IndirectImports2) },
 		{ list__append(IndirectImports2, IndirectUses1,
 			IndirectImports3) },
-		{ list__append(Items0, Items1, Items2) },
-		{ Module1 = module_imports(ModuleName, DirectImports1, 
-				OldIndirectImports, Items2, Error2) },
-		process_module_interfaces_2(Imports, IndirectImports3,
-				IndirectImports, Module1, Module)
+		{ list__append(ModItems0, Items, ModItems) },
+		{ Module1 = module_imports(ModuleName, ModAncestors,
+				ModInterfaceImports, ModImplementationImports,
+				ModIndirectImports, ModPublicChildren,
+				ModFactDeps, ModItems, ModError) },
+
+		process_module_long_interfaces(Imports, Ext,
+			IndirectImports3, IndirectImports, Module1, Module)
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred process_module_short_interfaces(list(string),
-		module_imports, module_imports, io__state, io__state).
-:- mode process_module_short_interfaces(in, in, out, di, uo) is det.
-
-process_module_short_interfaces(Imports, Module0, Module) -->
-	{ Module0 = module_imports(ModuleName, DirectImports0,
-		IndirectImports0, Items0, Error0) },
-
+process_module_indirect_imports(IndirectImports, Ext, Module0, Module) -->
 		% Treat indirectly imported items as if they were imported 
 		% using `:- use_module', since all uses of them in the `.int'
 		% files must be module qualified.
-	{ varset__init(Varset) },
-	{ term__context_init(Context) },
-	{ list__append(Items0, [module_defn(Varset, used) - Context], 
-		Items1) },
-
-	{ Module1 = module_imports(ModuleName, DirectImports0,
-		IndirectImports0, Items1, Error0) },
-
-	process_module_short_interfaces(Imports, ".int2", Module1, Module).
-
-
-:- pred process_module_short_interfaces(list(string), string, 
-		module_imports, module_imports, io__state, io__state).
-:- mode process_module_short_interfaces(in, in, in, out, di, uo) is det.
-
-process_module_short_interfaces([], _, Module, Module) --> [].
-process_module_short_interfaces([Import | Imports], Ext, Module0, Module) -->
-	{ Module0 = module_imports(ModuleName, DirectImports, IndirectImports0,
-			Items0, Error0) },
+	{ append_pseudo_decl(Module0, used, Module1) },
+	process_module_short_interfaces_transitively(IndirectImports,
+		Ext, Module1, Module).
+
+process_module_short_interfaces_transitively(Imports, Ext, Module0, Module) -->
+	process_module_short_interfaces(Imports, Ext, [], IndirectImports,
+		Module0, Module1),
+	( { IndirectImports = [] } ->
+		{ Module = Module1 }
+	;
+		process_module_short_interfaces_transitively(IndirectImports,
+			Ext, Module1, Module)
+	).
+
+process_module_short_interfaces([], _,
+		IndirectImports, IndirectImports, Module, Module) --> [].
+process_module_short_interfaces([Import | Imports], Ext, 
+		IndirectImports0, IndirectImports, Module0, Module) -->
+	{ Module0 = module_imports(ModuleName, ModAncestors,
+			ModInterfaceDeps, ModImplementationDeps,
+			ModIndirectImports0, ModPublicChildren, ModFactDeps,
+			ModItems0, ModError0) },
 	(
 		% check if the imported module has already been imported
 		{ Import = ModuleName
-		; list__member(Import, DirectImports)
-		; list__member(Import, IndirectImports0)
+		; list__member(Import, ModAncestors)
+		; list__member(Import, ModInterfaceDeps)
+		; list__member(Import, ModImplementationDeps)
+		; list__member(Import, ModIndirectImports0)
 		}
 	->
-		process_module_short_interfaces(Imports, Ext, Module0, Module)
+		process_module_short_interfaces(Imports, Ext,
+			IndirectImports0, IndirectImports, Module0, Module)
 	;
-		read_mod_short_interface(Import, Ext,
+		read_mod(Import, Ext,
 				"Reading short interface for module", yes,
-				ShortIntItems1, Error1),
-		% strip off the `:- interface' declaration at the start, if any
-		{
-			ShortIntItems1 = [ FirstItem | ShortIntItems2 ],
-			FirstItem = module_defn(_, interface) - _
-		->
-			Items1 = ShortIntItems2
-		;
-			Items1 = ShortIntItems1
-		},
-		{ Error1 \= no ->
-			Error2 = yes
-		;
-			Error2 = Error0
-		},
+				ShortIntItems, ShortIntError),
+		{ strip_off_interface_decl(ShortIntItems, Items) },
+		{ maybe_add_int_error(ShortIntError, ModError0, ModError) },
 
 		globals__io_lookup_bool_option(statistics, Statistics),
 		maybe_report_stats(Statistics),
 
-		{ get_dependencies(Items1, Imports1, Uses1) },
-		{ list__append(Imports, Imports1, Imports2) },
-		{ list__append(Imports2, Uses1, Imports3) },
-		{ list__append(Items0, Items1, Items2) },
-		{ IndirectImports1 = [Import | IndirectImports0] },
-		{ Module1 = module_imports(ModuleName, DirectImports,
-			IndirectImports1, Items2, Error2) },
-		process_module_short_interfaces(Imports3, Ext, Module1, Module)
+		{ ModIndirectImports = [Import | ModIndirectImports0] },
+		{ get_dependencies(Items, Imports1, Uses1) },
+		{ list__append(IndirectImports0, Imports1, IndirectImports1) },
+		{ list__append(IndirectImports1, Uses1, IndirectImports2) },
+		{ list__append(ModItems0, Items, ModItems) },
+		{ Module1 = module_imports(ModuleName, ModAncestors,
+			ModInterfaceDeps, ModImplementationDeps,
+			ModIndirectImports, ModPublicChildren, ModFactDeps,
+			ModItems, ModError) },
+		process_module_short_interfaces(Imports, Ext,
+			IndirectImports2, IndirectImports, Module1, Module)
+	).
+
+:- pred strip_off_interface_decl(item_list, item_list).
+:- mode strip_off_interface_decl(in, out) is det.
+
+% strip off the `:- interface' declaration at the start, if any
+
+strip_off_interface_decl(Items0, Items) :-
+	(
+		Items0 = [ FirstItem | Items1 ],
+		FirstItem = module_defn(_, interface) - _
+	->
+		Items = Items1
+	;
+		Items = Items0
+	).
+
+:- pred maybe_add_int_error(module_error, module_error, module_error).
+:- mode maybe_add_int_error(in, in, out) is det.
+
+maybe_add_int_error(InterfaceError, ModError0, ModError) :-
+	( InterfaceError \= no ->
+		ModError = yes
+	;
+		ModError = ModError0
 	).
 
 %-----------------------------------------------------------------------------%
 
+get_ancestors(ModuleName, Ancestors) :-
+	get_ancestors_2(ModuleName, [], Ancestors).
+	
+:- pred get_ancestors_2(module_name, list(module_name), list(module_name)).
+:- mode get_ancestors_2(in, in, out) is det.
+
+get_ancestors_2(unqualified(_), Ancestors, Ancestors).
+get_ancestors_2(qualified(Parent, _), Ancestors0, Ancestors) :-
+	Ancestors1 = [Parent | Ancestors0],
+	get_ancestors_2(Parent, Ancestors1, Ancestors).
+
+%-----------------------------------------------------------------------------%
+
+	% get_children(Items, IncludeDeps):
+	%	IncludeDeps is the list of sub-modules declared with
+	% 	`:- import_module' in Items.
+	%
+:- pred get_children(item_list, list(module_name)).
+:- mode get_children(in, out) is det.
+
+get_children(Items, IncludeDeps) :-
+	get_children_2(Items, [], IncludeDeps).
+
+:- pred get_children_2(item_list, list(module_name), list(module_name)).
+:- mode get_children_2(in, in, out) is det.
+
+get_children_2([], IncludeDeps, IncludeDeps).
+get_children_2([Item - _Context | Items], IncludeDeps0, IncludeDeps) :-
+	( 
+		Item = module_defn(_VarSet, include_module(Modules))
+	->
+		list__append(IncludeDeps0, Modules, IncludeDeps1)
+	;
+		IncludeDeps1 = IncludeDeps0
+	),
+	get_children_2(Items, IncludeDeps1, IncludeDeps).
+
+%-----------------------------------------------------------------------------%
+
 get_dependencies(Items, ImportDeps, UseDeps) :-
 	get_dependencies_2(Items, [], ImportDeps, [], UseDeps).
 
-:- pred get_dependencies_2(item_list, list(string), list(string), 
-		list(string), list(string)).
+:- pred get_dependencies_2(item_list, list(module_name), list(module_name), 
+		list(module_name), list(module_name)).
 :- mode get_dependencies_2(in, in, out, in, out) is det.
 
 get_dependencies_2([], ImportDeps, ImportDeps, UseDeps, UseDeps).
@@ -1708,13 +2339,13 @@
 	get_dependencies_2(Items, ImportDeps1, ImportDeps, UseDeps1, UseDeps).
 
 %-----------------------------------------------------------------------------%
+
 	% get the fact table dependencies for a module
 :- pred get_fact_table_dependencies(item_list, list(string)).
 :- mode get_fact_table_dependencies(in, out) is det.
 
 get_fact_table_dependencies(Items, Deps) :-
 	get_fact_table_dependencies_2(Items, [], Deps).
-
 
 :- pred get_fact_table_dependencies_2(item_list, list(string), list(string)).
 :- mode get_fact_table_dependencies_2(in, in, out) is det.
Index: compiler/opt_debug.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/opt_debug.m,v
retrieving revision 1.79
diff -u -u -r1.79 opt_debug.m
--- opt_debug.m	1998/01/13 10:13:05	1.79
+++ opt_debug.m	1998/02/16 06:48:14
@@ -186,6 +186,8 @@
 :- implementation.
 
 :- import_module llds_out, opt_util, vn_util, hlds_pred, globals, options.
+:- import_module prog_out.
+
 :- import_module int, set, map, string.
 
 opt_debug__msg(OptDebug, Msg) -->
@@ -685,8 +687,9 @@
 	string__append_list(["code_addr_const(", C_str, ")"], Str).
 opt_debug__dump_const(data_addr_const(data_addr(BaseName, VarName)), Str) :-
 	opt_debug__dump_data_name(VarName, N_str),
-	string__append_list(["data_addr_const(", BaseName, ", ", N_str, ")"],
-		Str).
+	prog_out__sym_name_to_string(BaseName, BaseName_str),
+	string__append_list(
+		["data_addr_const(", BaseName_str, ", ", N_str, ")"], Str).
 opt_debug__dump_const(label_entry(Label), Str) :-
 	opt_debug__dump_label(Label, LabelStr),
 	string__append_list(["label_entry(", LabelStr, ")"], Str).
@@ -785,23 +788,27 @@
 
 opt_debug__dump_proclabel(proc(Module, _PredOrFunc, PredModule,
 		PredName, Arity, ProcId), Str) :-
-	string__int_to_string(Arity, A_str),
-	proc_id_to_int(ProcId, Mode),
-	string__int_to_string(Mode, M_str),
 	( Module = PredModule ->
 		ExtraModule = ""
 	;
-		string__append(Module, "_", ExtraModule)
+		llds_out__sym_name_mangle(PredModule, PredModuleName),
+		string__append(PredModuleName, "_", ExtraModule)
 	),
-	string__append_list([ExtraModule, Module, "_", PredName,
+	llds_out__sym_name_mangle(Module, ModuleName),
+	string__int_to_string(Arity, A_str),
+	proc_id_to_int(ProcId, Mode),
+	string__int_to_string(Mode, M_str),
+	string__append_list([ExtraModule, ModuleName, "_", PredName,
 		"_", A_str, "_", M_str], Str).
 opt_debug__dump_proclabel(special_proc(Module, Pred, TypeModule,
 		Type, Arity, ProcId), Str) :-
+	llds_out__sym_name_mangle(Module, ModuleName),
+	llds_out__sym_name_mangle(TypeModule, TypeModuleName),
+	llds_out__qualify_name(TypeModuleName, Type, TypeName),
 	string__int_to_string(Arity, A_str),
 	proc_id_to_int(ProcId, Mode),
 	string__int_to_string(Mode, M_str),
-	llds_out__qualify_name(TypeModule, Type, TypeName),
-	string__append_list([Module, "_", Pred, "_",
+	string__append_list([ModuleName, "_", Pred, "_",
 		TypeName, "_", A_str, "_", M_str], Str).
 
 opt_debug__dump_bool(yes, "yes").
Index: compiler/opt_util.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/opt_util.m,v
retrieving revision 1.89
diff -u -u -r1.89 opt_util.m
--- opt_util.m	1998/01/16 07:05:39	1.89
+++ opt_util.m	1998/02/19 09:04:56
@@ -13,7 +13,7 @@
 :- module opt_util.
 
 :- interface.
-:- import_module bool, list, std_util.
+:- import_module bool, map, list, std_util.
 :- import_module llds.
 
 :- type instrmap == map(label, instruction).
@@ -312,7 +312,7 @@
 :- implementation.
 
 :- import_module exprn_aux, llds_out, hlds_pred.
-:- import_module int, string, set, map, require.
+:- import_module int, string, set, require.
 
 opt_util__get_prologue(Instrs0, ProcLabel, LabelInstr, Comments, Instrs) :-
 	opt_util__gather_comments(Instrs0, Comments1, Instrs1),
Index: compiler/optimize.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/optimize.m,v
retrieving revision 1.13
diff -u -u -r1.13 optimize.m
--- optimize.m	1998/01/23 12:56:47	1.13
+++ optimize.m	1998/02/25 02:05:50
@@ -14,7 +14,7 @@
 
 :- interface.
 
-:- import_module llds, io.
+:- import_module llds, io, list.
 
 :- pred optimize_main(list(c_procedure), list(c_procedure),
 	io__state, io__state).
@@ -27,7 +27,7 @@
 
 :- implementation.
 
-:- import_module bool, list, map, bimap, int, std_util.
+:- import_module bool, map, bimap, int, std_util.
 
 :- import_module jumpopt, labelopt, dupelim, peephole.
 :- import_module frameopt, delay_slot, value_number, options.
Index: compiler/options.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/options.m,v
retrieving revision 1.223
diff -u -u -r1.223 options.m
--- options.m	1998/02/03 08:18:31	1.223
+++ options.m	1998/02/18 14:03:07
@@ -74,6 +74,7 @@
 	% Output options
 		;	make_short_interface
 		;	make_interface
+		;	make_private_interface
 		;	make_optimization_interface
 		;	make_transitive_opt_interface
 		;	generate_dependencies
@@ -339,6 +340,7 @@
 	generate_module_order 	-	bool(no),
 	make_short_interface	-	bool(no),
 	make_interface		-	bool(no),
+	make_private_interface	-	bool(no),
 	make_optimization_interface -	bool(no),
 	make_transitive_opt_interface -	bool(no),
 	convert_to_mercury 	-	bool(no),
@@ -635,6 +637,8 @@
 long_option("make-short-int",		make_short_interface).
 long_option("make-interface",		make_interface).
 long_option("make-int",			make_interface).
+long_option("make-private-interface",	make_private_interface).
+long_option("make-priv-int",		make_private_interface).
 long_option("make-optimization-interface",
 					make_optimization_interface).
 long_option("make-optimisation-interface",
@@ -1249,6 +1253,10 @@
 	io__write_string("\t\tWrite the module interface to `<module>.int',\n"),
 	io__write_string("\t\tand write the short interface to `<module>.int2'\n"),
 	io__write_string("\t\tThis option should only be used by mmake.\n"),
+	io__write_string("\t--make-priv-int, --make-private-interface\n"),
+	io__write_string("\t\tWrite the private interface to `<module>.int0'.\n"),
+	io__write_string("\t\tThis option should only be used by mmake.\n"),
+	io__write_string("\t--make-opt-int, --make-optimization-interface\n"),
 	io__write_string("\t--make-short-int, --make-short-interface\n"),
 	io__write_string("\t\tWrite the unqualified short interface to `<module>.int3'.\n"),
 	io__write_string("\t\tThis option should only be used by mmake.\n"),
@@ -1260,6 +1268,7 @@
 	io__write_string("\t--make-transitive-optimization-interface\n"),
 	io__write_string("\t\tOutput transitive optimization information\n"),
 	io__write_string("\t\tinto the `<module>.trans_opt' file.\n"),
+	io__write_string("\t\tThis option should only be used by mmake.\n"),
 	io__write_string("\t-G, --convert-to-goedel\n"),
 	io__write_string("\t\tConvert to Goedel. Output to file `<module>.loc'.\n"),
 	io__write_string("\t\tNote that some Mercury language constructs cannot\n"),
Index: compiler/passes_aux.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/passes_aux.m,v
retrieving revision 1.24
diff -u -u -r1.24 passes_aux.m
--- passes_aux.m	1998/01/23 12:56:48	1.24
+++ passes_aux.m	1998/02/25 02:31:36
@@ -14,7 +14,7 @@
 :- interface.
 
 :- import_module hlds_module, hlds_pred, prog_data.
-:- import_module io.
+:- import_module io, std_util, list, bool.
 
 %-----------------------------------------------------------------------------%
 
@@ -128,7 +128,7 @@
 
 :- import_module options, globals, hlds_out, prog_out, mode_util.
 :- import_module mercury_to_mercury.
-:- import_module bool, int, map, tree234, std_util, require, list.
+:- import_module int, map, tree234, require.
 :- import_module varset.
 
 process_all_nonimported_procs(Task, ModuleInfo0, ModuleInfo) -->
Index: compiler/polymorphism.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/polymorphism.m,v
retrieving revision 1.129
diff -u -u -r1.129 polymorphism.m
--- polymorphism.m	1998/02/25 00:11:30	1.129
+++ polymorphism.m	1998/02/26 04:14:33
@@ -374,12 +374,14 @@
 	% is much simpler to avoid introducing type_info arguments for it.
 	% Since both of these are really just assignment unifications, it
 	% is desirable to generate them inline.
-:- pred polymorphism__no_type_info_builtin(string, string, int).
+:- pred polymorphism__no_type_info_builtin(module_name, string, int).
 :- mode polymorphism__no_type_info_builtin(in, in, out) is semidet.
 
-polymorphism__no_type_info_builtin("mercury_builtin", "unsafe_type_cast", 2).
-polymorphism__no_type_info_builtin("mercury_builtin",
-		"unsafe_promise_unique", 2).
+polymorphism__no_type_info_builtin(MercuryBuiltin, "unsafe_type_cast", 2) :-
+	mercury_private_builtin_module(MercuryBuiltin).
+polymorphism__no_type_info_builtin(MercuryBuiltin,
+		"unsafe_promise_unique", 2) :-
+	mercury_private_builtin_module(MercuryBuiltin).
 
 %---------------------------------------------------------------------------%
 
@@ -516,8 +518,8 @@
 	list__length(ExtraHeadTypeclassInfoVars, NumExtraVars1),
 	NumExtraVars is NumExtraVars1 + NumExtraVars0,
 
-	list__duplicate(NumExtraVars, user_defined_mode(
-		qualified("mercury_builtin", "in"), []), ExtraModes),
+	in_mode(In),
+	list__duplicate(NumExtraVars, In, ExtraModes),
 	list__append(ExtraModes, ArgModes0, ArgModes),
 
 		% Make a map of the locations of the unconstrained typeinfos
@@ -641,8 +643,10 @@
 
 			{ module_info_get_predicate_table(ModuleInfo,
 				PredicateTable) },
+			{ mercury_public_builtin_module(MercuryBuiltin) },
 			{ predicate_table_search_pred_m_n_a(PredicateTable,
-				"mercury_builtin", "unify", 2, [CallPredId]) ->
+				MercuryBuiltin, "unify", 2, [CallPredId])
+			->
 				PredId = CallPredId
 			;
 				error("polymorphism.m: can't find `mercury_builtin:unify/2'")
@@ -691,9 +695,10 @@
 			{ module_info_get_predicate_table(ModuleInfo,
 				PredicateTable) },
 			{
+				mercury_private_builtin_module(PrivateBuiltin),
 				predicate_table_search_pred_m_n_a(
 				    PredicateTable,
-				    "mercury_builtin", "builtin_unify_pred", 2,
+				    PrivateBuiltin, "builtin_unify_pred", 2,
 				    [PredId0])
 			->
 				PredId = PredId0
@@ -798,8 +803,9 @@
 	% insert type_info types for all the inserted type_info vars
 	% into the arg-types list
 	%
+	{ mercury_private_builtin_module(PrivateBuiltin) },
 	{ MakeType = lambda([TypeVar::in, TypeInfoType::out] is det,
-		construct_type(qualified("mercury_builtin", "type_info") - 1,
+		construct_type(qualified(PrivateBuiltin, "type_info") - 1,
 			[term__variable(TypeVar)], TypeInfoType)) },
 	{ list__map(MakeType, PredTypeVars, TypeInfoTypes) },
 	{ list__append(TypeInfoTypes, OrigArgTypes0, OrigArgTypes) },
@@ -823,8 +829,7 @@
 		ArgNames0, ArgNames1),
 	( varset__search_name(TypeVarSet, TVar, TypeVarName) ->
 		string__append("TypeInfo_for_", TypeVarName, C_VarName),
-		Input = user_defined_mode(qualified("mercury_builtin", "in"),
-			[]),
+		in_mode(Input),
 		ArgNames = [yes(C_VarName - Input) | ArgNames1]
 	;
 		ArgNames = [no | ArgNames1]
@@ -1379,19 +1384,16 @@
 
 				% Make the goal for the call
 			varset__init(Empty),
-			term__context_init(EmptyContext),
-			ExtractSuperClass = 
-				qualified("mercury_builtin", 
+			mercury_private_builtin_module(PrivateBuiltin),
+			ExtractSuperClass = qualified(PrivateBuiltin, 
 					  "superclass_from_typeclass_info"),
-			TypeClassInfoTerm = term__functor(
-					term__atom("typeclass_info"), [],
-					EmptyContext),
-			IntTerm = term__functor(
-					term__atom("int"), [],
-					EmptyContext),
+			construct_type(qualified(PrivateBuiltin,
+					"typeclass_info") - 0,
+					[], TypeClassInfoType),
+			construct_type(unqualified("int") - 0, [], IntType),
 			get_pred_id_and_proc_id(ExtractSuperClass, predicate, 
 				Empty, 
-				[TypeClassInfoTerm, IntTerm, TypeClassInfoTerm],
+				[TypeClassInfoType, IntType, TypeClassInfoType],
 				ModuleInfo, PredId, ProcId),
 			Call = call(PredId, ProcId, 
 				[SubClassVar, IndexVar, Var],
@@ -1455,9 +1457,9 @@
 	base_typeclass_info__make_instance_string(InstanceTypes,
 		InstanceString),
 
-		% XXX I don't think we actually need to carry this string
+		% XXX I don't think we actually need to carry the module name
 		% around.
-	ModuleName = "some bogus string",
+	ModuleName = unqualified("some bogus module name"),
 	ConsId = base_typeclass_info_const(ModuleName, ClassId, InstanceString),
 	BaseTypeClassInfoTerm = functor(ConsId, []),
 
@@ -1480,7 +1482,8 @@
 
 		% build a unification to add the argvars to the
 		% base_typeclass_info
-	NewConsId = cons(qualified("mercury_builtin", "typeclass_info"), 1),
+	mercury_private_builtin_module(PrivateBuiltin),
+	NewConsId = cons(qualified(PrivateBuiltin, "typeclass_info"), 1),
 	NewArgVars = [BaseVar|ArgVars],
 	TypeClassInfoTerm = functor(NewConsId, NewArgVars),
 
@@ -1511,7 +1514,7 @@
 		% note that we could perhaps be more accurate than
 		% `ground(shared)', but it shouldn't make any
 		% difference.
-	InstConsId = cons( qualified("mercury_builtin", "typeclass_info"), 
+	InstConsId = cons( qualified(PrivateBuiltin, "typeclass_info"), 
 		NumArgVars),
 	instmap_delta_from_assoc_list(
 		[NewVar - 
@@ -1772,7 +1775,8 @@
 		% a type_info, we need to adjust its type.
 		% Since base_type_info_const cons_ids are handled
 		% specially, this should not cause problems.
-		construct_type(qualified("mercury_builtin", "type_info") - 1,
+		mercury_private_builtin_module(MercuryBuiltin),
+		construct_type(qualified(MercuryBuiltin, "type_info") - 1,
 			[Type], NewBaseVarType),
 		map__det_update(VarTypes0, BaseVar, NewBaseVarType, VarTypes),
 
@@ -1815,8 +1819,7 @@
 		CountVar, CountGoal, VarSet, VarTypes) :-
 	varset__new_var(VarSet0, CountVar, VarSet1),
 	varset__name_var(VarSet1, CountVar, "TypeArity", VarSet),
-	term__context_init(Context),
-	IntType = term__functor(term__atom("int"), [], Context),
+	construct_type(unqualified("int") - 0, [], IntType),
 	map__set(VarTypes0, CountVar, IntType, VarTypes),
 	polymorphism__init_with_int_constant(CountVar, NumTypeArgs, CountGoal).
 
@@ -1976,8 +1979,9 @@
 polymorphism__get_builtin_pred_id(Name, Arity, ModuleInfo, PredId) :-
 	module_info_get_predicate_table(ModuleInfo, PredicateTable),
 	(
+		mercury_private_builtin_module(PrivateBuiltin),
 		predicate_table_search_pred_m_n_a(PredicateTable,
-			"mercury_builtin", Name, Arity, [PredId1])
+			PrivateBuiltin, Name, Arity, [PredId1])
 	->
 		PredId = PredId1
 	;
@@ -2006,7 +2010,8 @@
 polymorphism__init_type_info_var(Type, ArgVars, Symbol, VarSet0, VarTypes0,
 			TypeInfoVar, TypeInfoGoal, VarSet, VarTypes) :-
 
-	ConsId = cons(qualified("mercury_builtin", Symbol), 1),
+	mercury_private_builtin_module(PrivateBuiltin),
+	ConsId = cons(qualified(PrivateBuiltin, Symbol), 1),
 	TypeInfoTerm = functor(ConsId, ArgVars),
 
 	% introduce a new variable
@@ -2032,7 +2037,7 @@
 		% note that we could perhaps be more accurate than
 		% `ground(shared)', but it shouldn't make any
 		% difference.
-	InstConsId = cons(qualified("mercury_builtin", Symbol), NumArgVars),
+	InstConsId = cons(qualified(PrivateBuiltin, Symbol), NumArgVars),
 	instmap_delta_from_assoc_list(
 		[TypeInfoVar - bound(unique, [functor(InstConsId, ArgInsts)])],
 		InstMapDelta),
@@ -2124,8 +2129,9 @@
 	string__int_to_string(VarNum, VarNumStr),
 	string__append("TypeInfo_", VarNumStr, Name),
 	varset__name_var(VarSet1, Var, Name, VarSet),
-	construct_type(qualified("mercury_builtin", Symbol) - 1,
-					[Type], UnifyPredType),
+	mercury_private_builtin_module(PrivateBuiltin),
+	construct_type(qualified(PrivateBuiltin, Symbol) - 1, [Type],
+			UnifyPredType),
 	map__set(VarTypes0, Var, UnifyPredType, VarTypes).
 
 %---------------------------------------------------------------------------%
@@ -2158,17 +2164,16 @@
 	varset__init(TVarSet0),
 	varset__new_var(TVarSet0, TVar, TVarSet),
 
-	term__context_init(EmptyContext),
-	ExtractTypeInfo = qualified("mercury_builtin",
+	mercury_private_builtin_module(PrivateBuiltin),
+	ExtractTypeInfo = qualified(PrivateBuiltin,
 				"type_info_from_typeclass_info"),
-	TypeClassInfoTerm = term__functor(term__atom("typeclass_info"), [],
-		EmptyContext),
-	IntTerm = term__functor(term__atom("int"), [], EmptyContext),
-	TypeInfoTerm = term__functor(term__atom("type_info"), 
-		[term__variable(TVar)], EmptyContext),
-
+	construct_type(qualified(PrivateBuiltin, "typeclass_info") - 0, [],
+		TypeClassInfoType),
+	construct_type(unqualified("int") - 0, [], IntType),
+	construct_type(qualified(PrivateBuiltin, "type_info") - 1,
+		[term__variable(TVar)], TypeInfoType),
 	get_pred_id_and_proc_id(ExtractTypeInfo, predicate, TVarSet, 
-		[TypeClassInfoTerm, IntTerm, TypeInfoTerm],
+		[TypeClassInfoType, IntType, TypeInfoType],
 		ModuleInfo, PredId, ProcId),
 	polymorphism__make_count_var(Index, VarSet0, VarTypes0, IndexVar,
 		IndexGoal, VarSet1, VarTypes1),
@@ -2342,7 +2347,8 @@
 	string__append("TypeClassInfo_for_", ClassName, Name),
 	varset__name_var(VarSet1, Var, Name, VarSet),
 
-	construct_type(qualified("mercury_builtin", "typeclass_info") - 0,
+	mercury_private_builtin_module(PrivateBuiltin),
+	construct_type(qualified(PrivateBuiltin, "typeclass_info") - 0,
 					[], DictionaryType),
 	map__set(VarTypes0, Var, DictionaryType, VarTypes).
 
Index: compiler/pragma_c_gen.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/pragma_c_gen.m,v
retrieving revision 1.13
diff -u -u -r1.13 pragma_c_gen.m
--- pragma_c_gen.m	1998/01/16 07:05:40	1.13
+++ pragma_c_gen.m	1998/02/16 06:48:14
@@ -31,8 +31,8 @@
 	hlds_goal_info::in, pragma_c_code_impl::in, code_tree::out,
 	code_info::in, code_info::out) is det.
 
-:- pred pragma_c_gen__struct_name(string::in, string::in, int::in, proc_id::in,
-	string::out) is det.
+:- pred pragma_c_gen__struct_name(module_name::in, string::in, int::in,
+	proc_id::in, string::out) is det.
 
 %---------------------------------------------------------------------------%
 
@@ -1002,7 +1002,7 @@
 %---------------------------------------------------------------------------%
 
 pragma_c_gen__struct_name(ModuleName, PredName, Arity, ProcId, StructName) :-
-	llds_out__name_mangle(ModuleName, MangledModuleName),
+	llds_out__sym_name_mangle(ModuleName, MangledModuleName),
 	llds_out__name_mangle(PredName, MangledPredName),
 	proc_id_to_int(ProcId, ProcNum),
 	string__int_to_string(Arity, ArityStr),
Index: compiler/prog_data.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/prog_data.m,v
retrieving revision 1.31
diff -u -u -r1.31 prog_data.m
--- prog_data.m	1998/01/13 10:13:24	1.31
+++ prog_data.m	1998/02/16 21:05:34
@@ -29,7 +29,7 @@
 				% the error/warning message, and the
 				% term to which it relates
 
-:- type program		
+:- type compilation_unit		
 	--->	module(
 			module_name,
 			item_list
@@ -452,8 +452,11 @@
 
 :- type module_defn	
 	--->	module(module_name)
+	;	end_module(module_name)
+
 	;	interface
 	;	implementation
+
 	;	imported
 		% This is used internally by the compiler,
 		% to identify declarations which originally
@@ -467,15 +470,18 @@
 		% applies to items from modules imported using
 		% `:- use_module', and items from `.opt'
 		% and `.int2' files.
-	;	external(sym_name_specifier)
 	;	opt_imported
 		% This is used internally by the compiler,
 		% to identify items which originally
 		% came from a .opt file.
-	;	end_module(module_name)
+
+	;	external(sym_name_specifier)
+
 	;	export(sym_list)
 	;	import(sym_list)
-	;	use(sym_list).
+	;	use(sym_list)
+
+	;	include_module(list(module_name)).
 
 :- type sym_list	
 	--->	sym(list(sym_specifier))
@@ -521,14 +527,14 @@
 	; 	binary_prefix 
 	; 	binary_postfix.
 :- type sym_name_specifier 
-	---> name(sym_name)
+	--->	name(sym_name)
 	;	name_arity(sym_name, arity).
 :- type sym_name 	
 	--->	unqualified(string)
 	;	qualified(module_specifier, string).
 
-:- type module_specifier ==	string.
-:- type module_name 	== 	string.
+:- type module_specifier ==	sym_name.
+:- type module_name 	== 	sym_name.
 :- type arity		==	int.
 
 	% Describes whether an item can be used without an 
Index: compiler/prog_io.m
===================================================================
RCS file: /home/mercury1/repository/mercury/compiler/prog_io.m,v
retrieving revision 1.169
diff -u -u -r1.169 prog_io.m
--- prog_io.m	1998/01/07 06:09:27	1.169
+++ prog_io.m	1998/02/19 09:06:58
@@ -56,7 +56,7 @@
 :- interface.
 
 :- import_module prog_data, prog_io_util.
-:- import_module list, io. 
+:- import_module bool, varset, term, list, io. 
 
 %-----------------------------------------------------------------------------%
 
@@ -77,20 +77,23 @@
 	;	yes	% some syntax errors
 	;	fatal.	% couldn't open the file
 
-:- pred prog_io__read_module(string, string, bool, module_error,
+:- type file_name == string.
+:- type dir_name == string.
+
+:- pred prog_io__read_module(file_name, module_name, bool, module_error,
 	message_list, item_list, io__state, io__state).
 :- mode prog_io__read_module(in, in, in, out, out, out, di, uo) is det.
 
 	% Same as prog_io__read_module, but use intermod_directories
 	% instead of search_directories when searching for the file.
-:- pred prog_io__read_opt_file(string, string, bool, module_error,
+:- pred prog_io__read_opt_file(file_name, module_name, bool, module_error,
 	message_list, item_list, io__state, io__state).
 :- mode prog_io__read_opt_file(in, in, in, out, out, out, di, uo) is det.
 
 	% search_for_file(Dirs, FileName, Found, IO0, IO)
 	%
 	% Search Dirs for FileName, opening the file if it is found.
-:- pred search_for_file(list(string), string, bool, io__state, io__state).
+:- pred search_for_file(list(dir_name), file_name, bool, io__state, io__state).
 :- mode search_for_file(in, in, out, di, uo) is det.
 
 	% parse_item(ModuleName, VarSet, Term, MaybeItem)
@@ -99,7 +102,7 @@
 	% otherwise it is bound to an appropriate error message.
 	% Qualify appropriate parts of the item, with ModuleName as the
 	% module name.
-:- pred parse_item(string, varset, term, maybe_item_and_context). 
+:- pred parse_item(module_name, varset, term, maybe_item_and_context). 
 :- mode parse_item(in, in, in, out) is det.
 
 	% parse_decl(ModuleName, VarSet, Term, Result)
@@ -108,10 +111,59 @@
 	% parsed item, otherwise it is bound to an appropriate error message.
 	% Qualify appropriate parts of the item, with ModuleName as the module
 	% name.
-:- pred parse_decl(string, varset, term, maybe_item_and_context).
+:- pred parse_decl(module_name, varset, term, maybe_item_and_context).
 :- mode parse_decl(in, in, in, out) is det.
 
 %-----------------------------------------------------------------------------%
+
+	%	A QualifiedTerm is one of
+	%		Name(Args)
+	%		Module:Name(Args)
+	%	(or if Args is empty, one of
+	%		Name
+	%		Module:Name)
+	%	where Module is a SymName.
+	%	For backwards compatibility, we allow `__'
+	%	as an alternative to `:'.
+
+	% sym_name_and_args takes a term and returns a sym_name and a list of
+	% argument terms.
+	% It fals if the input is not valid syntax for a QualifiedTerm.
+:- pred sym_name_and_args(term, sym_name, list(term)).
+:- mode sym_name_and_args(in, out, out) is semidet.
+
+	% parse_qualified_term/4 takes a term (and also the containing
+	% term, and a string describing the context from which it
+	% was called [e.g. "clause head"] and the containing term)
+	% and returns a sym_name and a list of argument terms.
+	% Returns an error on ill-formed input.
+	% See also parse_implicitly_qualified_term/5 (below).
+:- pred parse_qualified_term(term, term, string, maybe_functor).
+:- mode parse_qualified_term(in, in, in, out) is det.
+
+	% parse_implicitly_qualified_term(DefaultModName, Term,
+	%	ContainingTerm, Msg, Result):
+	%
+	% parse_implicitly_qualified_term/5 takes a default module name
+	% and a term,
+	% (and also the containing term, and a string describing
+	% the context from which it was called (e.g. "clause head"),
+	% and returns a sym_name and a list of argument terms.
+	% Returns an error on ill-formed input or a module qualifier that
+	% doesn't match the DefaultModName.
+	%
+	% Note: parse_qualified_term/4 is used for places where a symbol
+	% is _used_, in which case no default module name exists, whereas
+	% parse_implicitly_qualified_term/5 is used for places where a symbol
+	% is _defined_; in that case, there is a default module name (the
+	% name of the current module) -- specifying a module qualifier
+	% explicitly is redundant, but it is allowed, so long as the
+	% module qualifier specified matches the default.
+:- pred parse_implicitly_qualified_term(module_name, term, term, string,
+					maybe_functor).
+:- mode parse_implicitly_qualified_term(in, in, in, in, out) is det.
+
+%-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
 :- implementation.
@@ -120,8 +172,8 @@
 :- import_module prog_io_typeclass.
 :- import_module hlds_data, hlds_pred, prog_util, globals, options, (inst).
 :- import_module purity.
-:- import_module bool, int, string, std_util, parser, term_io, dir, require.
-:- import_module varset, term.
+
+:- import_module int, string, std_util, parser, term_io, dir, require.
 
 %-----------------------------------------------------------------------------%
 
@@ -142,11 +194,11 @@
 % and then reverse them afterwards.  (Using difference lists would require
 % late-input modes.)
 
-:- pred prog_io__read_module_2(string, string, bool, option, module_error,
-	message_list, item_list, io__state, io__state).
+:- pred prog_io__read_module_2(file_name, module_name, bool, option,
+		module_error, message_list, item_list, io__state, io__state).
 :- mode prog_io__read_module_2(in, in, in, in, out, out, out, di, uo) is det.
 
-prog_io__read_module_2(FileName, ModuleName, Search,
+prog_io__read_module_2(FileName, DefaultModuleName, Search,
 		SearchOpt, Error, Messages, Items) -->
 	( 
 		{ Search = yes }
@@ -159,15 +211,7 @@
 	),
 	search_for_file(Dirs, FileName, R),
 	( { R = yes } ->
-		read_all_items(ModuleName, RevMessages, RevItems0, Error0),
-		{
-		  get_end_module(RevItems0, RevItems, EndModule),
-		  list__reverse(RevMessages, Messages0),
-		  list__reverse(RevItems, Items0)
-		},
-		check_begin_module(ModuleName,
-				Messages0, Items0, Error0, EndModule,
-				FileName, Messages, Items, Error),
+		read_all_items(DefaultModuleName, Messages, Items, Error),
 		io__seen
 	;
 		io__progname_base("prog_io.m", Progname),
@@ -226,72 +270,46 @@
 	% and that the end_module declaration (if any) is correct,
 	% and construct the final parsing result.
 
-:- pred check_begin_module(string, message_list, item_list, module_error,
-		module_end, string, message_list, item_list, module_error,
-		io__state, io__state).
-:- mode check_begin_module(in, in, in, in, in, in, out, out, out, di, uo)
-		is det.
+:- pred check_end_module(module_end, message_list, item_list, module_error,
+		message_list, item_list, module_error, io__state, io__state).
+:- mode check_end_module(in, in, in, in, out, out, out, di, uo) is det.
 
-check_begin_module(ModuleName, Messages0, Items0, Error0, EndModule, FileName,
+check_end_module(EndModule, Messages0, Items0, Error0,
 		Messages, Items, Error) -->
-    globals__io_lookup_bool_option(warn_missing_module_name, WarnMissing),
-    globals__io_lookup_bool_option(warn_wrong_module_name, WarnWrong),
-
-    % check that the first item is a `:- module ModuleName'
-    % declaration
-
+    %
+    % double-check that the first item is a `:- module ModuleName'
+    % declaration, and remove it from the front of the item list
+    %
     {
-        Items0 = [module_defn(_VarSet, module(ModuleName1)) - Context
-              | Items1]
+        Items0 = [module_defn(_VarSet, module(ModuleName1)) - _Context1
+		| Items1]
     ->
+	Items = Items1,
+	%
         % check that the end module declaration (if any)
         % matches the begin module declaration 
-
-        ( %%% some [ModuleName2, Context2]
-	    (
-        	EndModule = yes(ModuleName2, Context2),
-        	ModuleName1 \= ModuleName2
-            )
+	%
+        (
+            EndModule = yes(ModuleName2, Context2),
+            ModuleName1 \= ModuleName2
         ->
 	    dummy_term_with_context(Context2, Term),
-            ThisError = 
-"Error: `:- end_module' declaration doesn't match `:- module' declaration"
-			- Term,
-            list__append([ThisError], Messages0, Messages),
-	    Items = Items1,
-            Error = yes
+            add_error(
+"`:- end_module' declaration doesn't match `:- module' declaration",
+			Term, Messages0, Messages),
+	    Error = yes
         ;
-	% check that the begin module declaration matches the expected name
-	% of the module
-	    ModuleName1 \= ModuleName,
-	    WarnWrong = yes
-	->
-	    dummy_term_with_context(Context, Term2),
-            ThisError =
-	        "Warning: incorrect module name in `:- module' declaration"
-		    - Term2,
-            Messages = [ThisError | Messages0],
-	    Items = Items1,
-	    Error = Error0
-	;
 	    Messages = Messages0,
-	    Items = Items1,
 	    Error = Error0
         )
     ;
-	( WarnMissing = yes ->
-	    term__context_init(FileName, 1, Context),
-	    dummy_term_with_context(Context, Term2),
-            ThisError = "Warning: module should start with a `:- module' declaration"
-		- Term2,
-            Messages = [ThisError | Messages0]
-	;
-	    Messages = Messages0
-	),
-	Items = Items0,
-	Error = Error0
+	% if there's no `:- module' declaration at this point, it is
+	% an internal error -- read_first_item should have inserted one
+	error("check_end_module: no `:- module' declaration")
     }.
 
+%-----------------------------------------------------------------------------%
+
 	% Create a dummy term.
 	% Used for error messages that are not associated with any
 	% particular term or context.
@@ -312,6 +330,7 @@
 	Term = term__functor(term__atom(""), [], Context).
 
 %-----------------------------------------------------------------------------%
+
  	% Read a source file from standard in, first reading in
 	% the input term by term and then parsing those terms and producing
 	% a high-level representation.
@@ -322,17 +341,168 @@
 	%	parsing stage 2 (terms -> items).
 	% The final stage produces a list of program items, each of
 	% which may be a declaration or a clause.
+	%
+	% We use a continuation-passing style here.
 
-:- pred read_all_items(string, message_list, item_list, module_error,
+:- pred read_all_items(module_name, message_list, item_list, module_error,
 			io__state, io__state).
 :- mode read_all_items(in, out, out, out, di, uo) is det.
 
 read_all_items(ModuleName, Messages, Items, Error) -->
+	%
+	% read all the items (the first one is handled specially)
+	%
 	io__input_stream(Stream),
 	io__input_stream_name(Stream, SourceFileName),
-	read_items_loop(ModuleName, SourceFileName, [], [], no,
+	read_first_item(ModuleName, SourceFileName,
+		RevMessages, RevItems0, Error0),
+
+	%
+	% get the end_module declaration (if any),
+	% check that it matches the initial module declaration (if any),
+	% and remove both of them from the final item list.
+	%
+	{ get_end_module(RevItems0, RevItems, EndModule) },
+	{ list__reverse(RevMessages, Messages0) },
+	{ list__reverse(RevItems, Items0) },
+	check_end_module(EndModule,
+			Messages0, Items0, Error0,
 			Messages, Items, Error).
 
+%
+% We need to jump through a few hoops when reading the first item,
+% to allow the initial `:- module' declaration to be optional.
+% The reason is that in order to parse an item, we need to know
+% which module it is defined in (because we do some module
+% qualification and checking of module qualifiers at parse time),
+% but the initial `:- module' declaration and the declaration
+% that follows it occur in different scopes, so we need to know
+% what it is that we're parsing before we can parse it!
+% We solve this dilemma by first parsing it in the root scope,
+% and then if it turns out to not be a `:- module' declaration
+% we reparse it in the default module scope.  Blecchh.
+%
+:- pred read_first_item(module_name, file_name,
+		message_list, item_list, module_error, io__state, io__state).
+:- mode read_first_item(in, in, out, out, out, di, uo) is det.
+
+read_first_item(DefaultModuleName, SourceFileName, Messages, Items, Error) -->
+
+	globals__io_lookup_bool_option(warn_missing_module_name, WarnMissing),
+	globals__io_lookup_bool_option(warn_wrong_module_name, WarnWrong),
+    
+	%
+	% parse the first term, treating it as occurring
+	% within the scope of the special "root" module
+	% (so that any `:- module' declaration is taken to
+	% be a non-nested module unless explicitly qualified).
+	%
+	parser__read_term(SourceFileName, MaybeFirstTerm),
+	{ root_module_name(RootModuleName) },
+	{ process_read_term(RootModuleName, MaybeFirstTerm, MaybeFirstItem) },
+	(
+	    %
+	    % apply and then skip `pragma source_file' decls,
+	    % by calling ourselves recursively with the new source
+	    % file name
+	    %
+	    { MaybeFirstItem = ok(FirstItem, _) },
+	    { FirstItem = pragma(source_file(NewSourceFileName)) }
+	->
+	    read_first_item(DefaultModuleName, NewSourceFileName,
+		Messages, Items, Error)
+	;
+	    %
+	    % check if the first term was a `:- module' decl
+	    %
+	    { MaybeFirstItem = ok(FirstItem, FirstContext) },
+	    { FirstItem = module_defn(_VarSet, ModuleDefn) },
+	    { ModuleDefn = module(StartModuleName) }
+	->
+	    
+	    %
+	    % if so, then check that it matches the expected
+	    % module name, and if not, report a warning
+	    %
+	    {
+		match_sym_name(StartModuleName, DefaultModuleName)

-- 
Fergus Henderson <fjh at cs.mu.oz.au>   |  "I have always known that the pursuit
WWW: <http://www.cs.mu.oz.au/~fjh>   |  of excellence is a lethal habit"
PGP: finger fjh at 128.250.37.3         |     -- the last words of T. S. Garp.



More information about the developers mailing list