aboutsummaryrefslogtreecommitdiffstats
path: root/java/droiddoc.go
blob: 6a5758b2f4fc836d548d039d4902a11acdf032b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
// Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package java

import (
	"android/soong/android"
	"android/soong/java/config"
	"fmt"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/google/blueprint"
)

var (
	javadoc = pctx.AndroidStaticRule("javadoc",
		blueprint.RuleParams{
			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
				`${config.JavadocCmd} -encoding UTF-8 @$out.rsp @$srcJarDir/list ` +
				`$opts $bootclasspathArgs $classpathArgs -sourcepath $sourcepath ` +
				`-d $outDir -quiet  && ` +
				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir $postDoclavaCmds`,
			CommandDeps: []string{
				"${config.ZipSyncCmd}",
				"${config.JavadocCmd}",
				"${config.SoongZipCmd}",
			},
			Rspfile:        "$out.rsp",
			RspfileContent: "$in",
			Restat:         true,
		},
		"outDir", "srcJarDir", "stubsDir", "srcJars", "opts",
		"bootclasspathArgs", "classpathArgs", "sourcepath", "docZip", "postDoclavaCmds")

	apiCheck = pctx.AndroidStaticRule("apiCheck",
		blueprint.RuleParams{
			Command: `( ${config.ApiCheckCmd} -JXmx1024m -J"classpath $classpath" $opts ` +
				`$apiFile $apiFileToCheck $removedApiFile $removedApiFileToCheck ` +
				`&& touch $out ) || (echo -e "$msg" ; exit 38)`,
			CommandDeps: []string{
				"${config.ApiCheckCmd}",
			},
		},
		"classpath", "opts", "apiFile", "apiFileToCheck", "removedApiFile", "removedApiFileToCheck", "msg")

	updateApi = pctx.AndroidStaticRule("updateApi",
		blueprint.RuleParams{
			Command: `( ( cp -f $apiFileToCheck $apiFile && cp -f $removedApiFileToCheck $removedApiFile ) ` +
				`&& touch $out ) || (echo failed to update public API ; exit 38)`,
		},
		"apiFile", "apiFileToCheck", "removedApiFile", "removedApiFileToCheck")

	metalava = pctx.AndroidStaticRule("metalava",
		blueprint.RuleParams{
			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
				`${config.JavaCmd} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
				`$bootclasspathArgs $classpathArgs -sourcepath $sourcepath --no-banner --color --quiet ` +
				`--stubs $stubsDir $opts && ` +
				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir`,
			CommandDeps: []string{
				"${config.ZipSyncCmd}",
				"${config.JavaCmd}",
				"${config.MetalavaJar}",
				"${config.JavadocCmd}",
				"${config.SoongZipCmd}",
			},
			Rspfile:        "$out.rsp",
			RspfileContent: "$in",
			Restat:         true,
		},
		"outDir", "srcJarDir", "stubsDir", "srcJars", "javaVersion", "bootclasspathArgs",
		"classpathArgs", "sourcepath", "opts", "docZip")
)

func init() {
	android.RegisterModuleType("doc_defaults", DocDefaultsFactory)

	android.RegisterModuleType("droiddoc", DroiddocFactory)
	android.RegisterModuleType("droiddoc_host", DroiddocHostFactory)
	android.RegisterModuleType("droiddoc_template", DroiddocTemplateFactory)
	android.RegisterModuleType("javadoc", JavadocFactory)
	android.RegisterModuleType("javadoc_host", JavadocHostFactory)
}

var (
	srcsLibTag = dependencyTag{name: "sources from javalib"}
)

type JavadocProperties struct {
	// list of source files used to compile the Java module.  May be .java, .logtags, .proto,
	// or .aidl files.
	Srcs []string `android:"arch_variant"`

	// list of directories rooted at the Android.bp file that will
	// be added to the search paths for finding source files when passing package names.
	Local_sourcepaths []string

	// list of source files that should not be used to build the Java module.
	// This is most useful in the arch/multilib variants to remove non-common files
	// filegroup or genrule can be included within this property.
	Exclude_srcs []string `android:"arch_variant"`

	// list of java libraries that will be in the classpath.
	Libs []string `android:"arch_variant"`

	// don't build against the framework libraries (legacy-test, core-junit,
	// ext, and framework for device targets)
	No_framework_libs *bool

	// the java library (in classpath) for documentation that provides java srcs and srcjars.
	Srcs_lib *string

	// the base dirs under srcs_lib will be scanned for java srcs.
	Srcs_lib_whitelist_dirs []string

	// the sub dirs under srcs_lib_whitelist_dirs will be scanned for java srcs.
	Srcs_lib_whitelist_pkgs []string

	// If set to false, don't allow this module(-docs.zip) to be exported. Defaults to true.
	Installable *bool

	// if not blank, set to the version of the sdk to compile against
	Sdk_version *string `android:"arch_variant"`

	Aidl struct {
		// Top level directories to pass to aidl tool
		Include_dirs []string

		// Directories rooted at the Android.bp file to pass to aidl tool
		Local_include_dirs []string
	}

	// If not blank, set the java version passed to javadoc as -source
	Java_version *string
}

type ApiToCheck struct {
	// path to the API txt file that the new API extracted from source code is checked
	// against. The path can be local to the module or from other module (via :module syntax).
	Api_file *string

	// path to the API txt file that the new @removed API extractd from source code is
	// checked against. The path can be local to the module or from other module (via
	// :module syntax).
	Removed_api_file *string

	// Arguments to the apicheck tool.
	Args *string
}

type DroiddocProperties struct {
	// directory relative to top of the source tree that contains doc templates files.
	Custom_template *string

	// directories relative to top of the source tree which contains html/jd files.
	Html_dirs []string

	// set a value in the Clearsilver hdf namespace.
	Hdf []string

	// proofread file contains all of the text content of the javadocs concatenated into one file,
	// suitable for spell-checking and other goodness.
	Proofread_file *string

	// a todo file lists the program elements that are missing documentation.
	// At some point, this might be improved to show more warnings.
	Todo_file *string

	// directory under current module source that provide additional resources (images).
	Resourcesdir *string

	// resources output directory under out/soong/.intermediates.
	Resourcesoutdir *string

	// local files that are used within user customized droiddoc options.
	Arg_files []string

	// user customized droiddoc args.
	// Available variables for substitution:
	//
	//  $(location <label>): the path to the arg_files with name <label>
	Args *string

	// names of the output files used in args that will be generated
	Out []string

	// if set to true, collect the values used by the Dev tools and
	// write them in files packaged with the SDK. Defaults to false.
	Write_sdk_values *bool

	// index.html under current module will be copied to docs out dir, if not null.
	Static_doc_index_redirect *string

	// source.properties under current module will be copied to docs out dir, if not null.
	Static_doc_properties *string

	// a list of files under current module source dir which contains known tags in Java sources.
	// filegroup or genrule can be included within this property.
	Knowntags []string

	// the tag name used to distinguish if the API files belong to public/system/test.
	Api_tag_name *string

	// the generated public API filename by Doclava.
	Api_filename *string

	// the generated public Dex API filename by Doclava.
	Dex_api_filename *string

	// the generated private API filename by Doclava.
	Private_api_filename *string

	// the generated private Dex API filename by Doclava.
	Private_dex_api_filename *string

	// the generated removed API filename by Doclava.
	Removed_api_filename *string

	// the generated removed Dex API filename by Doclava.
	Removed_dex_api_filename *string

	// mapping of dex signatures to source file and line number. This is a temporary property and
	// will be deleted; you probably shouldn't be using it.
	Dex_mapping_filename *string

	// the generated exact API filename by Doclava.
	Exact_api_filename *string

	// if set to false, don't allow droiddoc to generate stubs source files. Defaults to true.
	Create_stubs *bool

	Check_api struct {
		Last_released ApiToCheck

		Current ApiToCheck
	}

	// if set to true, create stubs through Metalava instead of Doclava. Javadoc/Doclava is
	// currently still used for documentation generation, and will be replaced by Dokka soon.
	Metalava_enabled *bool

	// user can specify the version of previous released API file in order to do compatibility check.
	Metalava_previous_api *string

	// is set to true, Metalava will allow framework SDK to contain annotations.
	Metalava_annotations_enabled *bool

	// a list of top-level directories containing files to merge annotations from.
	Metalava_merge_annotations_dirs []string
}

type Javadoc struct {
	android.ModuleBase
	android.DefaultableModuleBase

	properties JavadocProperties

	srcJars     android.Paths
	srcFiles    android.Paths
	sourcepaths android.Paths

	docZip      android.WritablePath
	stubsSrcJar android.WritablePath
}

func (j *Javadoc) Srcs() android.Paths {
	return android.Paths{j.stubsSrcJar}
}

var _ android.SourceFileProducer = (*Javadoc)(nil)

type Droiddoc struct {
	Javadoc

	properties        DroiddocProperties
	apiFile           android.WritablePath
	dexApiFile        android.WritablePath
	privateApiFile    android.WritablePath
	privateDexApiFile android.WritablePath
	removedApiFile    android.WritablePath
	removedDexApiFile android.WritablePath
	exactApiFile      android.WritablePath
	apiMappingFile    android.WritablePath

	checkCurrentApiTimestamp      android.WritablePath
	updateCurrentApiTimestamp     android.WritablePath
	checkLastReleasedApiTimestamp android.WritablePath

	annotationsZip android.WritablePath

	apiFilePath android.Path
}

type ApiFilePath interface {
	ApiFilePath() android.Path
}

func InitDroiddocModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
	android.InitAndroidArchModule(module, hod, android.MultilibCommon)
	android.InitDefaultableModule(module)
}

func JavadocFactory() android.Module {
	module := &Javadoc{}

	module.AddProperties(&module.properties)

	InitDroiddocModule(module, android.HostAndDeviceSupported)
	return module
}

func JavadocHostFactory() android.Module {
	module := &Javadoc{}

	module.AddProperties(&module.properties)

	InitDroiddocModule(module, android.HostSupported)
	return module
}

func DroiddocFactory() android.Module {
	module := &Droiddoc{}

	module.AddProperties(&module.properties,
		&module.Javadoc.properties)

	InitDroiddocModule(module, android.HostAndDeviceSupported)
	return module
}

func DroiddocHostFactory() android.Module {
	module := &Droiddoc{}

	module.AddProperties(&module.properties,
		&module.Javadoc.properties)

	InitDroiddocModule(module, android.HostSupported)
	return module
}

func (j *Javadoc) sdkVersion() string {
	return String(j.properties.Sdk_version)
}

func (j *Javadoc) minSdkVersion() string {
	return j.sdkVersion()
}

func (j *Javadoc) addDeps(ctx android.BottomUpMutatorContext) {
	if ctx.Device() {
		sdkDep := decodeSdkDep(ctx, sdkContext(j))
		if sdkDep.useDefaultLibs {
			ctx.AddDependency(ctx.Module(), bootClasspathTag, config.DefaultBootclasspathLibraries...)
			if ctx.Config().TargetOpenJDK9() {
				ctx.AddDependency(ctx.Module(), systemModulesTag, config.DefaultSystemModules)
			}
			if !Bool(j.properties.No_framework_libs) {
				ctx.AddDependency(ctx.Module(), libTag, []string{"ext", "framework"}...)
			}
		} else if sdkDep.useModule {
			if ctx.Config().TargetOpenJDK9() {
				ctx.AddDependency(ctx.Module(), systemModulesTag, sdkDep.systemModules)
			}
			ctx.AddDependency(ctx.Module(), bootClasspathTag, sdkDep.modules...)
		}
	}

	ctx.AddDependency(ctx.Module(), libTag, j.properties.Libs...)
	if j.properties.Srcs_lib != nil {
		ctx.AddDependency(ctx.Module(), srcsLibTag, *j.properties.Srcs_lib)
	}

	android.ExtractSourcesDeps(ctx, j.properties.Srcs)

	// exclude_srcs may contain filegroup or genrule.
	android.ExtractSourcesDeps(ctx, j.properties.Exclude_srcs)
}

func (j *Javadoc) genWhitelistPathPrefixes(whitelistPathPrefixes map[string]bool) {
	for _, dir := range j.properties.Srcs_lib_whitelist_dirs {
		for _, pkg := range j.properties.Srcs_lib_whitelist_pkgs {
			// convert foo.bar.baz to foo/bar/baz
			pkgAsPath := filepath.Join(strings.Split(pkg, ".")...)
			prefix := filepath.Join(dir, pkgAsPath)
			if _, found := whitelistPathPrefixes[prefix]; !found {
				whitelistPathPrefixes[prefix] = true
			}
		}
	}
}

func (j *Javadoc) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
	var flags javaBuilderFlags

	// aidl flags.
	aidlFlags := j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
	if len(aidlFlags) > 0 {
		// optimization.
		ctx.Variable(pctx, "aidlFlags", strings.Join(aidlFlags, " "))
		flags.aidlFlags = "$aidlFlags"
	}

	return flags
}

func (j *Javadoc) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
	aidlIncludeDirs android.Paths) []string {

	aidlIncludes := android.PathsForModuleSrc(ctx, j.properties.Aidl.Local_include_dirs)
	aidlIncludes = append(aidlIncludes, android.PathsForSource(ctx, j.properties.Aidl.Include_dirs)...)

	var flags []string
	if aidlPreprocess.Valid() {
		flags = append(flags, "-p"+aidlPreprocess.String())
	} else {
		flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
	}

	flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
	flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
	if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
		flags = append(flags, "-I"+src.String())
	}

	return flags
}

func (j *Javadoc) genSources(ctx android.ModuleContext, srcFiles android.Paths,
	flags javaBuilderFlags) android.Paths {

	outSrcFiles := make(android.Paths, 0, len(srcFiles))

	for _, srcFile := range srcFiles {
		switch srcFile.Ext() {
		case ".aidl":
			javaFile := genAidl(ctx, srcFile, flags.aidlFlags)
			outSrcFiles = append(outSrcFiles, javaFile)
		default:
			outSrcFiles = append(outSrcFiles, srcFile)
		}
	}

	return outSrcFiles
}

func (j *Javadoc) collectDeps(ctx android.ModuleContext) deps {
	var deps deps

	sdkDep := decodeSdkDep(ctx, sdkContext(j))
	if sdkDep.invalidVersion {
		ctx.AddMissingDependencies(sdkDep.modules)
	} else if sdkDep.useFiles {
		deps.bootClasspath = append(deps.bootClasspath, sdkDep.jars...)
	}

	ctx.VisitDirectDeps(func(module android.Module) {
		otherName := ctx.OtherModuleName(module)
		tag := ctx.OtherModuleDependencyTag(module)

		switch tag {
		case bootClasspathTag:
			if dep, ok := module.(Dependency); ok {
				deps.bootClasspath = append(deps.bootClasspath, dep.ImplementationJars()...)
			} else {
				panic(fmt.Errorf("unknown dependency %q for %q", otherName, ctx.ModuleName()))
			}
		case libTag:
			switch dep := module.(type) {
			case Dependency:
				deps.classpath = append(deps.classpath, dep.ImplementationJars()...)
			case SdkLibraryDependency:
				sdkVersion := j.sdkVersion()
				linkType := javaSdk
				if strings.HasPrefix(sdkVersion, "system_") || strings.HasPrefix(sdkVersion, "test_") {
					linkType = javaSystem
				} else if sdkVersion == "" {
					linkType = javaPlatform
				}
				deps.classpath = append(deps.classpath, dep.ImplementationJars(linkType)...)
			case android.SourceFileProducer:
				checkProducesJars(ctx, dep)
				deps.classpath = append(deps.classpath, dep.Srcs()...)
			default:
				ctx.ModuleErrorf("depends on non-java module %q", otherName)
			}
		case srcsLibTag:
			switch dep := module.(type) {
			case Dependency:
				srcs := dep.(SrcDependency).CompiledSrcs()
				whitelistPathPrefixes := make(map[string]bool)
				j.genWhitelistPathPrefixes(whitelistPathPrefixes)
				for _, src := range srcs {
					if _, ok := src.(android.WritablePath); ok { // generated sources
						deps.srcs = append(deps.srcs, src)
					} else { // select source path for documentation based on whitelist path prefixs.
						for k, _ := range whitelistPathPrefixes {
							if strings.HasPrefix(src.Rel(), k) {
								deps.srcs = append(deps.srcs, src)
								break
							}
						}
					}
				}
				deps.srcJars = append(deps.srcJars, dep.(SrcDependency).CompiledSrcJars()...)
			default:
				ctx.ModuleErrorf("depends on non-java module %q", otherName)
			}
		case systemModulesTag:
			if deps.systemModules != nil {
				panic("Found two system module dependencies")
			}
			sm := module.(*SystemModules)
			if sm.outputFile == nil {
				panic("Missing directory for system module dependency")
			}
			deps.systemModules = sm.outputFile
		}
	})
	// do not pass exclude_srcs directly when expanding srcFiles since exclude_srcs
	// may contain filegroup or genrule.
	srcFiles := ctx.ExpandSources(j.properties.Srcs, j.properties.Exclude_srcs)
	flags := j.collectBuilderFlags(ctx, deps)
	srcFiles = j.genSources(ctx, srcFiles, flags)

	// srcs may depend on some genrule output.
	j.srcJars = srcFiles.FilterByExt(".srcjar")
	j.srcJars = append(j.srcJars, deps.srcJars...)

	j.srcFiles = srcFiles.FilterOutByExt(".srcjar")
	j.srcFiles = append(j.srcFiles, deps.srcs...)

	j.docZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"docs.zip")
	j.stubsSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")

	if j.properties.Local_sourcepaths == nil {
		j.properties.Local_sourcepaths = append(j.properties.Local_sourcepaths, ".")
	}
	j.sourcepaths = android.PathsForModuleSrc(ctx, j.properties.Local_sourcepaths)

	return deps
}

func (j *Javadoc) DepsMutator(ctx android.BottomUpMutatorContext) {
	j.addDeps(ctx)
}

func (j *Javadoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
	deps := j.collectDeps(ctx)

	var implicits android.Paths
	implicits = append(implicits, deps.bootClasspath...)
	implicits = append(implicits, deps.classpath...)

	var bootClasspathArgs, classpathArgs string

	javaVersion := getJavaVersion(ctx, String(j.properties.Java_version), sdkContext(j))
	if len(deps.bootClasspath) > 0 {
		var systemModules classpath
		if deps.systemModules != nil {
			systemModules = append(systemModules, deps.systemModules)
		}
		bootClasspathArgs = systemModules.FormJavaSystemModulesPath("--system ", ctx.Device())
		bootClasspathArgs = bootClasspathArgs + " --patch-module java.base=."
	}
	if len(deps.classpath.Strings()) > 0 {
		classpathArgs = "-classpath " + strings.Join(deps.classpath.Strings(), ":")
	}

	implicits = append(implicits, j.srcJars...)

	opts := "-source " + javaVersion + " -J-Xmx1024m -XDignore.symbol.file -Xdoclint:none"

	ctx.Build(pctx, android.BuildParams{
		Rule:           javadoc,
		Description:    "Javadoc",
		Output:         j.stubsSrcJar,
		ImplicitOutput: j.docZip,
		Inputs:         j.srcFiles,
		Implicits:      implicits,
		Args: map[string]string{
			"outDir":            android.PathForModuleOut(ctx, "docs", "out").String(),
			"srcJarDir":         android.PathForModuleOut(ctx, "docs", "srcjars").String(),
			"stubsDir":          android.PathForModuleOut(ctx, "docs", "stubsDir").String(),
			"srcJars":           strings.Join(j.srcJars.Strings(), " "),
			"opts":              opts,
			"bootclasspathArgs": bootClasspathArgs,
			"classpathArgs":     classpathArgs,
			"sourcepath":        strings.Join(j.sourcepaths.Strings(), ":"),
			"docZip":            j.docZip.String(),
		},
	})
}

func (d *Droiddoc) checkCurrentApi() bool {
	if String(d.properties.Check_api.Current.Api_file) != "" &&
		String(d.properties.Check_api.Current.Removed_api_file) != "" {
		return true
	} else if String(d.properties.Check_api.Current.Api_file) != "" {
		panic("check_api.current.removed_api_file: has to be non empty!")
	} else if String(d.properties.Check_api.Current.Removed_api_file) != "" {
		panic("check_api.current.api_file: has to be non empty!")
	}

	return false
}

func (d *Droiddoc) checkLastReleasedApi() bool {
	if String(d.properties.Check_api.Last_released.Api_file) != "" &&
		String(d.properties.Check_api.Last_released.Removed_api_file) != "" {
		return true
	} else if String(d.properties.Check_api.Last_released.Api_file) != "" {
		panic("check_api.last_released.removed_api_file: has to be non empty!")
	} else if String(d.properties.Check_api.Last_released.Removed_api_file) != "" {
		panic("check_api.last_released.api_file: has to be non empty!")
	}

	return false
}

func (d *Droiddoc) DepsMutator(ctx android.BottomUpMutatorContext) {
	d.Javadoc.addDeps(ctx)

	if String(d.properties.Custom_template) != "" {
		ctx.AddDependency(ctx.Module(), droiddocTemplateTag, String(d.properties.Custom_template))
	}

	// extra_arg_files may contains filegroup or genrule.
	android.ExtractSourcesDeps(ctx, d.properties.Arg_files)

	// knowntags may contain filegroup or genrule.
	android.ExtractSourcesDeps(ctx, d.properties.Knowntags)

	if String(d.properties.Static_doc_index_redirect) != "" {
		android.ExtractSourceDeps(ctx, d.properties.Static_doc_index_redirect)
	}

	if String(d.properties.Static_doc_properties) != "" {
		android.ExtractSourceDeps(ctx, d.properties.Static_doc_properties)
	}

	if d.checkCurrentApi() {
		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Api_file)
		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Removed_api_file)
	}

	if d.checkLastReleasedApi() {
		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Api_file)
		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Removed_api_file)
	}

	if String(d.properties.Metalava_previous_api) != "" {
		android.ExtractSourceDeps(ctx, d.properties.Metalava_previous_api)
	}
}

func (d *Droiddoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
	deps := d.Javadoc.collectDeps(ctx)

	var implicits android.Paths
	implicits = append(implicits, deps.bootClasspath...)
	implicits = append(implicits, deps.classpath...)

	var bootClasspathArgs string
	javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), sdkContext(d))
	// Doclava has problem with "-source 1.9", so override javaVersion when Doclava
	// is running with EXPERIMENTAL_USE_OPENJDK9=true. And eventually Doclava will be
	// replaced by Metalava.
	if !Bool(d.properties.Metalava_enabled) {
		javaVersion = "1.8"
	}
	// continue to use -bootclasspath even if Metalava under -source 1.9 is enabled
	// since it doesn't support system modules yet.
	if len(deps.bootClasspath.Strings()) > 0 {
		// For OpenJDK 8 we can use -bootclasspath to define the core libraries code.
		bootClasspathArgs = deps.bootClasspath.FormJavaClassPath("-bootclasspath")
	}
	classpathArgs := deps.classpath.FormJavaClassPath("-classpath")

	argFiles := ctx.ExpandSources(d.properties.Arg_files, nil)
	argFilesMap := map[string]android.Path{}

	for _, f := range argFiles {
		implicits = append(implicits, f)
		if _, exists := argFilesMap[f.Rel()]; !exists {
			argFilesMap[f.Rel()] = f
		} else {
			ctx.ModuleErrorf("multiple arg_files for %q, %q and %q",
				f, argFilesMap[f.Rel()], f.Rel())
		}
	}

	args, err := android.Expand(String(d.properties.Args), func(name string) (string, error) {
		if strings.HasPrefix(name, "location ") {
			label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
			if f, ok := argFilesMap[label]; ok {
				return f.String(), nil
			} else {
				return "", fmt.Errorf("unknown location label %q", label)
			}
		} else if name == "genDir" {
			return android.PathForModuleGen(ctx).String(), nil
		}
		return "", fmt.Errorf("unknown variable '$(%s)'", name)
	})

	if err != nil {
		ctx.PropertyErrorf("args", "%s", err.Error())
		return
	}

	genDocsForMetalava := false
	var metalavaArgs string
	if Bool(d.properties.Metalava_enabled) {
		if strings.Contains(args, "--generate-documentation") {
			if !strings.Contains(args, "-nodocs") {
				genDocsForMetalava = true
			}
			// TODO(nanzhang): Add a Soong property to handle documentation args.
			metalavaArgs = strings.Split(args, "--generate-documentation")[0]
		} else {
			metalavaArgs = args
		}
	}

	var templateDir, htmlDirArgs, htmlDir2Args string
	if !Bool(d.properties.Metalava_enabled) || genDocsForMetalava {
		if String(d.properties.Custom_template) == "" {
			// TODO: This is almost always droiddoc-templates-sdk
			ctx.PropertyErrorf("custom_template", "must specify a template")
		}

		ctx.VisitDirectDepsWithTag(droiddocTemplateTag, func(m android.Module) {
			if t, ok := m.(*DroiddocTemplate); ok {
				implicits = append(implicits, t.deps...)
				templateDir = t.dir.String()
			} else {
				ctx.PropertyErrorf("custom_template", "module %q is not a droiddoc_template", ctx.OtherModuleName(m))
			}
		})

		if len(d.properties.Html_dirs) > 0 {
			htmlDir := android.PathForModuleSrc(ctx, d.properties.Html_dirs[0])
			implicits = append(implicits, ctx.Glob(htmlDir.Join(ctx, "**/*").String(), nil)...)
			htmlDirArgs = "-htmldir " + htmlDir.String()
		}

		if len(d.properties.Html_dirs) > 1 {
			htmlDir2 := android.PathForModuleSrc(ctx, d.properties.Html_dirs[1])
			implicits = append(implicits, ctx.Glob(htmlDir2.Join(ctx, "**/*").String(), nil)...)
			htmlDir2Args = "-htmldir2 " + htmlDir2.String()
		}

		if len(d.properties.Html_dirs) > 2 {
			ctx.PropertyErrorf("html_dirs", "Droiddoc only supports up to 2 html dirs")
		}

		knownTags := ctx.ExpandSources(d.properties.Knowntags, nil)
		implicits = append(implicits, knownTags...)

		for _, kt := range knownTags {
			args = args + " -knowntags " + kt.String()
		}

		for _, hdf := range d.properties.Hdf {
			args = args + " -hdf " + hdf
		}

		if String(d.properties.Proofread_file) != "" {
			proofreadFile := android.PathForModuleOut(ctx, String(d.properties.Proofread_file))
			args = args + " -proofread " + proofreadFile.String()
		}

		if String(d.properties.Todo_file) != "" {
			// tricky part:
			// we should not compute full path for todo_file through PathForModuleOut().
			// the non-standard doclet will get the full path relative to "-o".
			args = args + " -todo " + String(d.properties.Todo_file)
		}

		if String(d.properties.Resourcesdir) != "" {
			// TODO: should we add files under resourcesDir to the implicits? It seems that
			// resourcesDir is one sub dir of htmlDir
			resourcesDir := android.PathForModuleSrc(ctx, String(d.properties.Resourcesdir))
			args = args + " -resourcesdir " + resourcesDir.String()
		}

		if String(d.properties.Resourcesoutdir) != "" {
			// TODO: it seems -resourceoutdir reference/android/images/ didn't get generated anywhere.
			args = args + " -resourcesoutdir " + String(d.properties.Resourcesoutdir)
		}
	}

	var docArgsForMetalava string
	if Bool(d.properties.Metalava_enabled) && genDocsForMetalava {
		docArgsForMetalava = strings.Split(args, "--generate-documentation")[1]
	}

	var implicitOutputs android.WritablePaths

	if d.checkCurrentApi() || d.checkLastReleasedApi() || String(d.properties.Api_filename) != "" {
		d.apiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_api.txt")
		args = args + " -api " + d.apiFile.String()
		metalavaArgs = metalavaArgs + " --api " + d.apiFile.String()
		implicitOutputs = append(implicitOutputs, d.apiFile)
		d.apiFilePath = d.apiFile
	}

	if d.checkCurrentApi() || d.checkLastReleasedApi() || String(d.properties.Removed_api_filename) != "" {
		d.removedApiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_removed.txt")
		args = args + " -removedApi " + d.removedApiFile.String()
		metalavaArgs = metalavaArgs + " --removed-api " + d.removedApiFile.String()
		implicitOutputs = append(implicitOutputs, d.removedApiFile)
	}

	if String(d.properties.Private_api_filename) != "" {
		d.privateApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_api_filename))
		args = args + " -privateApi " + d.privateApiFile.String()
		metalavaArgs = metalavaArgs + " --private-api " + d.privateApiFile.String()
		implicitOutputs = append(implicitOutputs, d.privateApiFile)
	}

	if String(d.properties.Dex_api_filename) != "" {
		d.dexApiFile = android.PathForModuleOut(ctx, String(d.properties.Dex_api_filename))
		args = args + " -dexApi " + d.dexApiFile.String()
		implicitOutputs = append(implicitOutputs, d.dexApiFile)
	}

	if String(d.properties.Private_dex_api_filename) != "" {
		d.privateDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_dex_api_filename))
		args = args + " -privateDexApi " + d.privateDexApiFile.String()
		metalavaArgs = metalavaArgs + " --private-dex-api " + d.privateDexApiFile.String()
		implicitOutputs = append(implicitOutputs, d.privateDexApiFile)
	}

	if String(d.properties.Removed_dex_api_filename) != "" {
		d.removedDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Removed_dex_api_filename))
		args = args + " -removedDexApi " + d.removedDexApiFile.String()
		metalavaArgs = metalavaArgs + " --removed-dex-api " + d.removedDexApiFile.String()
		implicitOutputs = append(implicitOutputs, d.removedDexApiFile)
	}

	if String(d.properties.Exact_api_filename) != "" {
		d.exactApiFile = android.PathForModuleOut(ctx, String(d.properties.Exact_api_filename))
		args = args + " -exactApi " + d.exactApiFile.String()
		metalavaArgs = metalavaArgs + " --exact-api " + d.exactApiFile.String()
		implicitOutputs = append(implicitOutputs, d.exactApiFile)
	}

	if String(d.properties.Dex_mapping_filename) != "" {
		d.apiMappingFile = android.PathForModuleOut(ctx, String(d.properties.Dex_mapping_filename))
		args = args + " -apiMapping " + d.apiMappingFile.String()
		// Omitted: metalava support
		implicitOutputs = append(implicitOutputs, d.apiMappingFile)
	}

	implicits = append(implicits, d.Javadoc.srcJars...)

	implicitOutputs = append(implicitOutputs, d.Javadoc.docZip)
	for _, o := range d.properties.Out {
		implicitOutputs = append(implicitOutputs, android.PathForModuleGen(ctx, o))
	}

	jsilver := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "jsilver.jar")
	doclava := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "doclava.jar")

	var date string
	if runtime.GOOS == "darwin" {
		date = `date -r`
	} else {
		date = `date -d`
	}

	doclavaOpts := "-source " + javaVersion + " -J-Xmx1600m -J-XX:-OmitStackTraceInFastThrow -XDignore.symbol.file " +
		"-doclet com.google.doclava.Doclava -docletpath " + jsilver.String() + ":" + doclava.String() + " " +
		"-templatedir " + templateDir + " " + htmlDirArgs + " " + htmlDir2Args + " " +
		"-hdf page.build " + ctx.Config().BuildId() + "-" + ctx.Config().BuildNumberFromFile() + " " +
		`-hdf page.now "$$(` + date + ` @$$(cat ` + ctx.Config().Getenv("BUILD_DATETIME_FILE") + `) "+%d %b %Y %k:%M")" `

	if !Bool(d.properties.Metalava_enabled) {
		opts := doclavaOpts + args

		implicits = append(implicits, jsilver)
		implicits = append(implicits, doclava)

		if BoolDefault(d.properties.Create_stubs, true) {
			opts += " -stubs " + android.PathForModuleOut(ctx, "docs", "stubsDir").String()
		}

		if Bool(d.properties.Write_sdk_values) {
			opts += " -sdkvalues " + android.PathForModuleOut(ctx, "docs", "out").String()
		}

		var postDoclavaCmds string
		if String(d.properties.Static_doc_index_redirect) != "" {
			static_doc_index_redirect := ctx.ExpandSource(String(d.properties.Static_doc_index_redirect),
				"static_doc_index_redirect")
			implicits = append(implicits, static_doc_index_redirect)
			postDoclavaCmds += " && cp " + static_doc_index_redirect.String() + " " +
				android.PathForModuleOut(ctx, "docs", "out", "index.html").String()
		}

		if String(d.properties.Static_doc_properties) != "" {
			static_doc_properties := ctx.ExpandSource(String(d.properties.Static_doc_properties),
				"static_doc_properties")
			implicits = append(implicits, static_doc_properties)
			postDoclavaCmds += " && cp " + static_doc_properties.String() + " " +
				android.PathForModuleOut(ctx, "docs", "out", "source.properties").String()
		}

		ctx.Build(pctx, android.BuildParams{
			Rule:            javadoc,
			Description:     "Droiddoc",
			Output:          d.Javadoc.stubsSrcJar,
			Inputs:          d.Javadoc.srcFiles,
			Implicits:       implicits,
			ImplicitOutputs: implicitOutputs,
			Args: map[string]string{
				"outDir":            android.PathForModuleOut(ctx, "docs", "out").String(),
				"srcJarDir":         android.PathForModuleOut(ctx, "docs", "srcjars").String(),
				"stubsDir":          android.PathForModuleOut(ctx, "docs", "stubsDir").String(),
				"srcJars":           strings.Join(d.Javadoc.srcJars.Strings(), " "),
				"opts":              opts,
				"bootclasspathArgs": bootClasspathArgs,
				"classpathArgs":     classpathArgs,
				"sourcepath":        strings.Join(d.Javadoc.sourcepaths.Strings(), ":"),
				"docZip":            d.Javadoc.docZip.String(),
				"postDoclavaCmds":   postDoclavaCmds,
			},
		})
	} else {
		opts := metalavaArgs

		buildArgs := map[string]string{
			"outDir":            android.PathForModuleOut(ctx, "docs", "out").String(),
			"srcJarDir":         android.PathForModuleOut(ctx, "docs", "srcjars").String(),
			"stubsDir":          android.PathForModuleOut(ctx, "docs", "stubsDir").String(),
			"srcJars":           strings.Join(d.Javadoc.srcJars.Strings(), " "),
			"javaVersion":       javaVersion,
			"bootclasspathArgs": bootClasspathArgs,
			"classpathArgs":     classpathArgs,
			"sourcepath":        strings.Join(d.Javadoc.sourcepaths.Strings(), ":"),
			"docZip":            d.Javadoc.docZip.String(),
		}

		var previousApi android.Path
		if String(d.properties.Metalava_previous_api) != "" {
			previousApi = ctx.ExpandSource(String(d.properties.Metalava_previous_api),
				"metalava_previous_api")
			opts += " --previous-api " + previousApi.String()
			implicits = append(implicits, previousApi)
		}

		if Bool(d.properties.Metalava_annotations_enabled) {
			if String(d.properties.Metalava_previous_api) == "" {
				ctx.PropertyErrorf("metalava_previous_api",
					"has to be non-empty if annotations was enabled!")
			}
			opts += " --include-annotations --migrate-nullness"

			d.annotationsZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"_annotations.zip")
			implicitOutputs = append(implicitOutputs, d.annotationsZip)

			if len(d.properties.Metalava_merge_annotations_dirs) == 0 {
				ctx.PropertyErrorf("metalava_merge_annotations_dirs",
					"has to be non-empty if annotations was enabled!")
			}
			mergeAnnotationsDirs := android.PathsForSource(ctx, d.properties.Metalava_merge_annotations_dirs)

			opts += " --extract-annotations " + d.annotationsZip.String()
			for _, mergeAnnotationsDir := range mergeAnnotationsDirs {
				opts += " --merge-annotations " + mergeAnnotationsDir.String()
			}
			// TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
			opts += " --hide HiddenTypedefConstant --hide SuperfluousPrefix --hide AnnotationExtraction"
		}

		if genDocsForMetalava {
			opts += " --doc-stubs " + android.PathForModuleOut(ctx, "docs", "docStubsDir").String() +
				" --write-doc-stubs-source-list $outDir/doc_stubs_src_list " +
				" --generate-documentation ${config.JavadocCmd} -encoding UTF-8 DOC_STUBS_SOURCE_LIST " +
				doclavaOpts + docArgsForMetalava + bootClasspathArgs + " " + classpathArgs + " " + " -sourcepath " +
				android.PathForModuleOut(ctx, "docs", "docStubsDir").String() + " -quiet -d $outDir "
			implicits = append(implicits, jsilver)
			implicits = append(implicits, doclava)
		}

		buildArgs["opts"] = opts
		ctx.Build(pctx, android.BuildParams{
			Rule:            metalava,
			Description:     "Metalava",
			Output:          d.Javadoc.stubsSrcJar,
			Inputs:          d.Javadoc.srcFiles,
			Implicits:       implicits,
			ImplicitOutputs: implicitOutputs,
			Args:            buildArgs,
		})
	}

	java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")

	checkApiClasspath := classpath{jsilver, doclava, android.PathForSource(ctx, java8Home, "lib/tools.jar")}

	if d.checkCurrentApi() && !ctx.Config().IsPdkBuild() {
		d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "check_current_api.timestamp")

		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Api_file),
			"check_api.current.api_file")
		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Removed_api_file),
			"check_api.current_removed_api_file")

		ctx.Build(pctx, android.BuildParams{
			Rule:        apiCheck,
			Description: "Current API check",
			Output:      d.checkCurrentApiTimestamp,
			Inputs:      nil,
			Implicits: append(android.Paths{apiFile, removedApiFile, d.apiFile, d.removedApiFile},
				checkApiClasspath...),
			Args: map[string]string{
				"classpath":             checkApiClasspath.FormJavaClassPath(""),
				"opts":                  String(d.properties.Check_api.Current.Args),
				"apiFile":               apiFile.String(),
				"apiFileToCheck":        d.apiFile.String(),
				"removedApiFile":        removedApiFile.String(),
				"removedApiFileToCheck": d.removedApiFile.String(),
				"msg": fmt.Sprintf(`\n******************************\n`+
					`You have tried to change the API from what has been previously approved.\n\n`+
					`To make these errors go away, you have two choices:\n`+
					`   1. You can add '@hide' javadoc comments to the methods, etc. listed in the\n`+
					`      errors above.\n\n`+
					`   2. You can update current.txt by executing the following command:\n`+
					`         make %s-update-current-api\n\n`+
					`      To submit the revised current.txt to the main Android repository,\n`+
					`      you will need approval.\n`+
					`******************************\n`, ctx.ModuleName()),
			},
		})

		d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "update_current_api.timestamp")

		ctx.Build(pctx, android.BuildParams{
			Rule:        updateApi,
			Description: "update current API",
			Output:      d.updateCurrentApiTimestamp,
			Implicits:   append(android.Paths{}, apiFile, removedApiFile, d.apiFile, d.removedApiFile),
			Args: map[string]string{
				"apiFile":               apiFile.String(),
				"apiFileToCheck":        d.apiFile.String(),
				"removedApiFile":        removedApiFile.String(),
				"removedApiFileToCheck": d.removedApiFile.String(),
			},
		})
	}
	if d.checkLastReleasedApi() && !ctx.Config().IsPdkBuild() {
		d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "check_last_released_api.timestamp")

		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Api_file),
			"check_api.last_released.api_file")
		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Removed_api_file),
			"check_api.last_released.removed_api_file")

		ctx.Build(pctx, android.BuildParams{
			Rule:        apiCheck,
			Description: "Last Released API check",
			Output:      d.checkLastReleasedApiTimestamp,
			Inputs:      nil,
			Implicits: append(android.Paths{apiFile, removedApiFile, d.apiFile, d.removedApiFile},
				checkApiClasspath...),
			Args: map[string]string{
				"classpath":             checkApiClasspath.FormJavaClassPath(""),
				"opts":                  String(d.properties.Check_api.Last_released.Args),
				"apiFile":               apiFile.String(),
				"apiFileToCheck":        d.apiFile.String(),
				"removedApiFile":        removedApiFile.String(),
				"removedApiFileToCheck": d.removedApiFile.String(),
				"msg": `\n******************************\n` +
					`You have tried to change the API from what has been previously released in\n` +
					`an SDK.  Please fix the errors listed above.\n` +
					`******************************\n`,
			},
		})
	}
}

func (d *Droiddoc) ApiFilePath() android.Path {
	return d.apiFilePath
}

var droiddocTemplateTag = dependencyTag{name: "droiddoc-template"}

type DroiddocTemplateProperties struct {
	// path to the directory containing the droiddoc templates.
	Path *string
}

type DroiddocTemplate struct {
	android.ModuleBase

	properties DroiddocTemplateProperties

	deps android.Paths
	dir  android.Path
}

func DroiddocTemplateFactory() android.Module {
	module := &DroiddocTemplate{}
	module.AddProperties(&module.properties)
	android.InitAndroidModule(module)
	return module
}

func (d *DroiddocTemplate) DepsMutator(android.BottomUpMutatorContext) {}

func (d *DroiddocTemplate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
	path := android.PathForModuleSrc(ctx, String(d.properties.Path))
	d.dir = path
	d.deps = ctx.Glob(path.Join(ctx, "**/*").String(), nil)
}

//
// Defaults
//
type DocDefaults struct {
	android.ModuleBase
	android.DefaultsModuleBase
}

func (*DocDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
}

func (d *DocDefaults) DepsMutator(ctx android.BottomUpMutatorContext) {
}

func DocDefaultsFactory() android.Module {
	module := &DocDefaults{}

	module.AddProperties(
		&JavadocProperties{},
		&DroiddocProperties{},
	)

	android.InitDefaultsModule(module)

	return module
}