1/*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import * as ts from 'typescript';
17import type { CommandLineOptions } from '../lib/CommandLineOptions';
18import { formTscOptions } from './ts-compiler/FormTscOptions';
19import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic';
20import { consoleLog } from '../lib/TypeScriptLinter';
21import type { LintOptions } from '../lib/LintOptions';
22import { TSCCompiledProgramWithDiagnostics } from '../lib/ts-diagnostics/TSCCompiledProgram';
23
24function compile(cmdOptions: CommandLineOptions, overrideCompilerOptions: ts.CompilerOptions): ts.Program {
25  const createProgramOptions = formTscOptions(cmdOptions, overrideCompilerOptions);
26  const program = ts.createProgram(createProgramOptions);
27  // Log Tsc errors if needed
28  if (cmdOptions.logTscErrors) {
29    const diagnostics = ts.getPreEmitDiagnostics(program);
30    logTscDiagnostic(diagnostics, consoleLog);
31  }
32  return program;
33}
34
35export function compileLintOptions(cmdOptions: CommandLineOptions): LintOptions {
36  const strict = compile(cmdOptions, getOverrideCompilerOptions(true));
37  const nonStrict = compile(cmdOptions, getOverrideCompilerOptions(false));
38  return {
39    cmdOptions: cmdOptions,
40    tscCompiledProgram: new TSCCompiledProgramWithDiagnostics(strict, nonStrict, cmdOptions.inputFiles),
41    isEtsFile: true
42  };
43}
44
45function getOverrideCompilerOptions(strict: boolean): ts.CompilerOptions {
46  return {
47    strict: false,
48    alwaysStrict: false,
49    noImplicitAny: false,
50    noImplicitThis: false,
51    strictBindCallApply: false,
52    useUnknownInCatchVariables: false,
53    strictNullChecks: strict,
54    strictFunctionTypes: strict,
55    strictPropertyInitialization: strict,
56    noImplicitReturns: strict
57  };
58}
59