repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ScriptExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.parser.ParseError;
import com.semmle.util.data.Pair;
import com.semmle.util.trap.TrapWriter.Label;
/** Extract a stand-alone JavaScript script. */
public class ScriptExtractor implements IExtractor {
private ExtractorConfig config;
public ScriptExtractor(ExtractorConfig config) {
this.config = config;
}
/** True if files with the given extension should always be treated as modules. */
private boolean isAlwaysModule(String extension) {
return extension.equals(".mjs") || extension.equals(".es6") || extension.equals(".es");
}
@Override
public LoCInfo extract(TextualExtractor textualExtractor) {
LocationManager locationManager = textualExtractor.getLocationManager();
String source = textualExtractor.getSource();
String shebangLine = null, shebangLineTerm = null;
if (source.startsWith("#!")) {
// at this point, it's safe to assume we're extracting Node.js code
// (unless we were specifically told otherwise)
if (config.getPlatform() != Platform.WEB) config = config.withPlatform(Platform.NODE);
// skip shebang (but populate it as part of the lines relation below)
int eolPos = source.indexOf('\n');
if (eolPos > 0) {
shebangLine = source.substring(0, eolPos);
shebangLineTerm = "\n";
source = source.substring(eolPos + 1);
} else {
shebangLine = source;
shebangLineTerm = "";
source = "";
}
locationManager.setStart(2, 1);
}
// Some file extensions are interpreted as modules by default.
if (isAlwaysModule(locationManager.getSourceFileExtension())) {
if (config.getSourceType() == SourceType.AUTO)
config = config.withSourceType(SourceType.MODULE);
}
ScopeManager scopeManager =
new ScopeManager(textualExtractor.getTrapwriter(), config.getEcmaVersion());
Label toplevelLabel = null;
LoCInfo loc;
try {
Pair<Label, LoCInfo> res =
new JSExtractor(config).extract(textualExtractor, source, 0, scopeManager);
toplevelLabel = res.fst();
loc = res.snd();
} catch (ParseError e) {
e.setPosition(locationManager.translatePosition(e.getPosition()));
throw e.asUserError();
}
if (shebangLine != null)
textualExtractor.extractLine(shebangLine, shebangLineTerm, 0, toplevelLabel);
return loc;
}
}
| 2,537 | 33.767123 | 92 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/Main.java | package com.semmle.js.extractor;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.semmle.js.extractor.ExtractorConfig.HTMLHandling;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.extractor.FileExtractor.FileType;
import com.semmle.js.extractor.trapcache.DefaultTrapCache;
import com.semmle.js.extractor.trapcache.DummyTrapCache;
import com.semmle.js.extractor.trapcache.ITrapCache;
import com.semmle.js.parser.ParsedProject;
import com.semmle.js.parser.TypeScriptParser;
import com.semmle.ts.extractor.TypeExtractor;
import com.semmle.ts.extractor.TypeTable;
import com.semmle.util.data.StringUtil;
import com.semmle.util.data.UnitParser;
import com.semmle.util.exception.ResourceError;
import com.semmle.util.exception.UserError;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.files.FileUtil;
import com.semmle.util.files.PathMatcher;
import com.semmle.util.io.WholeIO;
import com.semmle.util.language.LegacyLanguage;
import com.semmle.util.process.ArgsParser;
import com.semmle.util.process.ArgsParser.FileMode;
import com.semmle.util.process.Env;
import com.semmle.util.process.Env.Var;
import com.semmle.util.trap.TrapWriter;
/** The main entry point of the JavaScript extractor. */
public class Main {
/**
* A version identifier that should be updated every time the extractor changes in such a way that
* it may produce different tuples for the same file under the same {@link ExtractorConfig}.
*/
public static final String EXTRACTOR_VERSION = "2020-04-01";
public static final Pattern NEWLINE = Pattern.compile("\n");
// symbolic constants for command line parameter names
private static final String P_ABORT_ON_PARSE_ERRORS = "--abort-on-parse-errors";
private static final String P_DEBUG_EXCLUSIONS = "--debug-exclusions";
private static final String P_DEFAULT_ENCODING = "--default-encoding";
private static final String P_EXCLUDE = "--exclude";
private static final String P_EXPERIMENTAL = "--experimental";
private static final String P_EXTERNS = "--externs";
private static final String P_EXTRACT_PROGRAM_TEXT = "--extract-program-text";
private static final String P_FILE_TYPE = "--file-type";
private static final String P_HTML = "--html";
private static final String P_INCLUDE = "--include";
private static final String P_PLATFORM = "--platform";
private static final String P_QUIET = "--quiet";
private static final String P_SOURCE_TYPE = "--source-type";
private static final String P_TRAP_CACHE = "--trap-cache";
private static final String P_TRAP_CACHE_BOUND = "--trap-cache-bound";
private static final String P_TYPESCRIPT = "--typescript";
private static final String P_TYPESCRIPT_FULL = "--typescript-full";
private static final String P_TYPESCRIPT_RAM = "--typescript-ram";
// symbolic constants for deprecated command line parameter names
private static final String P_EXCLUDE_PATH = "--exclude-path";
private static final String P_TOLERATE_PARSE_ERRORS = "--tolerate-parse-errors";
private static final String P_NODEJS = "--nodejs";
private static final String P_MOZ_EXTENSIONS = "--mozExtensions";
private static final String P_JSCRIPT = "--jscript";
private static final String P_HELP = "--help";
private static final String P_ECMA_VERSION = "--ecmaVersion";
private final ExtractorOutputConfig extractorOutputConfig;
private ExtractorConfig extractorConfig;
private PathMatcher includeMatcher, excludeMatcher;
private FileExtractor fileExtractor;
private ExtractorState extractorState;
private Set<File> projectFiles = new LinkedHashSet<>();
private Set<File> files = new LinkedHashSet<>();
private final Set<File> extractedFiles = new LinkedHashSet<>();
/* used to detect cyclic directory hierarchies */
private final Set<String> seenDirectories = new LinkedHashSet<>();
/**
* If true, the extractor state is shared with other extraction jobs.
*
* <p>This is used by the test runner.
*/
private boolean hasSharedExtractorState = false;
public Main(ExtractorOutputConfig extractorOutputConfig) {
this.extractorOutputConfig = extractorOutputConfig;
this.extractorState = new ExtractorState();
}
public Main(ExtractorOutputConfig extractorOutputConfig, ExtractorState extractorState) {
this.extractorOutputConfig = extractorOutputConfig;
this.extractorState = extractorState;
this.hasSharedExtractorState = true;
}
public void run(String[] args) {
ArgsParser ap = addArgs(new ArgsParser(args));
ap.parse();
extractorConfig = parseJSOptions(ap);
ITrapCache trapCache;
if (ap.has(P_TRAP_CACHE)) {
Long sizeBound = null;
if (ap.has(P_TRAP_CACHE_BOUND)) {
String tcb = ap.getString(P_TRAP_CACHE_BOUND);
sizeBound = DefaultTrapCache.asFileSize(tcb);
if (sizeBound == null) ap.error("Invalid TRAP cache size bound: " + tcb);
}
trapCache = new DefaultTrapCache(ap.getString(P_TRAP_CACHE), sizeBound, EXTRACTOR_VERSION);
} else {
if (ap.has(P_TRAP_CACHE_BOUND))
ap.error(
P_TRAP_CACHE_BOUND + " should only be specified together with " + P_TRAP_CACHE + ".");
trapCache = new DummyTrapCache();
}
fileExtractor = new FileExtractor(extractorConfig, extractorOutputConfig, trapCache);
setupMatchers(ap);
collectFiles(ap);
if (files.isEmpty()) {
verboseLog(ap, "Nothing to extract.");
return;
}
// Sort files for determinism
projectFiles = projectFiles.stream()
.sorted(AutoBuild.FILE_ORDERING)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
files = files.stream()
.sorted(AutoBuild.FILE_ORDERING)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
// Extract HTML files first, as they may contain embedded TypeScript code
for (File file : files) {
if (FileType.forFile(file, extractorConfig) == FileType.HTML) {
ensureFileIsExtracted(file, ap);
}
}
TypeScriptParser tsParser = extractorState.getTypeScriptParser();
tsParser.setTypescriptRam(extractorConfig.getTypeScriptRam());
if (containsTypeScriptFiles()) {
tsParser.verifyInstallation(!ap.has(P_QUIET));
}
for (File projectFile : projectFiles) {
long start = verboseLogStartTimer(ap, "Opening project " + projectFile);
ParsedProject project = tsParser.openProject(projectFile, DependencyInstallationResult.empty, extractorConfig.getVirtualSourceRoot());
verboseLogEndTimer(ap, start);
// Extract all files belonging to this project which are also matched
// by our include/exclude filters.
List<File> filesToExtract = new ArrayList<>();
for (File sourceFile : project.getOwnFiles()) {
File normalizedFile = normalizeFile(sourceFile);
if ((files.contains(normalizedFile) || extractorState.getSnippets().containsKey(normalizedFile.toPath()))
&& !extractedFiles.contains(sourceFile.getAbsoluteFile())
&& FileType.TYPESCRIPT.getExtensions().contains(FileUtil.extension(sourceFile))) {
filesToExtract.add(sourceFile);
}
}
tsParser.prepareFiles(filesToExtract);
for (int i = 0; i < filesToExtract.size(); ++i) {
ensureFileIsExtracted(filesToExtract.get(i), ap);
}
// Close the project to free memory. This does not need to be in a `finally` as
// the project is not a system resource.
tsParser.closeProject(projectFile);
}
if (!projectFiles.isEmpty()) {
// Extract all the types discovered when extracting the ASTs.
TypeTable typeTable = tsParser.getTypeTable();
extractTypeTable(projectFiles.iterator().next(), typeTable);
}
List<File> remainingTypescriptFiles = new ArrayList<>();
for (File f : files) {
if (!extractedFiles.contains(f.getAbsoluteFile())
&& FileType.forFileExtension(f) == FileType.TYPESCRIPT) {
remainingTypescriptFiles.add(f);
}
}
if (!remainingTypescriptFiles.isEmpty()) {
tsParser.prepareFiles(remainingTypescriptFiles);
for (File f : remainingTypescriptFiles) {
ensureFileIsExtracted(f, ap);
}
}
// The TypeScript compiler instance is no longer needed - free up some memory.
if (hasSharedExtractorState) {
tsParser.reset(); // This is called from a test runner, so keep the process alive.
} else {
tsParser.killProcess();
}
// Extract files that were not part of a project.
for (File f : files) {
if (isFileDerivedFromTypeScriptFile(f))
continue;
ensureFileIsExtracted(f, ap);
}
}
/**
* Returns true if the given path is likely the output of compiling a TypeScript file
* which we have already extracted.
*/
private boolean isFileDerivedFromTypeScriptFile(File path) {
String name = path.getName();
if (!name.endsWith(".js"))
return false;
String stem = name.substring(0, name.length() - ".js".length());
for (String ext : FileType.TYPESCRIPT.getExtensions()) {
if (new File(path.getParent(), stem + ext).exists()) {
return true;
}
}
return false;
}
private void extractTypeTable(File fileHandle, TypeTable table) {
TrapWriter trapWriter =
extractorOutputConfig
.getTrapWriterFactory()
.mkTrapWriter(
new File(
fileHandle.getParentFile(),
fileHandle.getName() + ".codeql-typescript-typetable"));
try {
new TypeExtractor(trapWriter, table).extract();
} finally {
FileUtil.close(trapWriter);
}
}
private void ensureFileIsExtracted(File f, ArgsParser ap) {
if (!extractedFiles.add(f.getAbsoluteFile())) {
// The file has already been extracted as part of a project.
return;
}
long start = verboseLogStartTimer(ap, "Extracting " + f);
try {
fileExtractor.extract(f.getAbsoluteFile(), extractorState);
verboseLogEndTimer(ap, start);
} catch (IOException e) {
throw new ResourceError("Extraction of " + f + " failed.", e);
}
}
private void verboseLog(ArgsParser ap, String message) {
if (!ap.has(P_QUIET)) {
System.out.println(message);
}
}
private long verboseLogStartTimer(ArgsParser ap, String message) {
if (!ap.has(P_QUIET)) {
System.out.print(message + "...");
System.out.flush();
}
return System.currentTimeMillis();
}
private void verboseLogEndTimer(ArgsParser ap, long start) {
long end = System.currentTimeMillis();
if (!ap.has(P_QUIET)) {
System.out.println(" done (" + (end - start) / 1000 + " seconds).");
}
}
/** Returns true if the project contains a TypeScript file to be extracted. */
private boolean containsTypeScriptFiles() {
for (File file : files) {
// The file headers have already been checked, so don't use I/O.
if (FileType.forFileExtension(file) == FileType.TYPESCRIPT) {
return true;
}
}
return false;
}
public void collectFiles(ArgsParser ap) {
for (File f : getFilesArg(ap))
collectFiles(f, true);
}
private List<File> getFilesArg(ArgsParser ap) {
return ap.getOneOrMoreFiles("files", FileMode.FILE_OR_DIRECTORY_MUST_EXIST);
}
public void setupMatchers(ArgsParser ap) {
Set<String> includes = new LinkedHashSet<>();
// only extract HTML and JS by default
addIncludesFor(includes, FileType.HTML);
addIncludesFor(includes, FileType.JS);
// extract TypeScript if `--typescript` or `--typescript-full` was specified
if (getTypeScriptMode(ap) != TypeScriptMode.NONE) addIncludesFor(includes, FileType.TYPESCRIPT);
// add explicit include patterns
for (String pattern : ap.getZeroOrMore(P_INCLUDE))
addPathPattern(includes, System.getProperty("user.dir"), pattern);
this.includeMatcher = new PathMatcher(includes);
// if we are extracting (potential) Node.js code, we also want to
// include package.json files, and files without extension
if (getPlatform(ap) != Platform.WEB) {
PathMatcher innerIncludeMatcher = this.includeMatcher;
this.includeMatcher =
new PathMatcher("**/package.json") {
@Override
public boolean matches(String path) {
// match files without extension
String basename = path.substring(path.lastIndexOf(File.separatorChar) + 1);
if (FileUtil.extension(basename).isEmpty()) return true;
// match package.json and anything matched by the inner matcher
return super.matches(path) || innerIncludeMatcher.matches(path);
}
};
}
Set<String> excludes = new LinkedHashSet<>();
for (String pattern : ap.getZeroOrMore(P_EXCLUDE))
addPathPattern(excludes, System.getProperty("user.dir"), pattern);
for (String excl : ap.getZeroOrMore(P_EXCLUDE_PATH)) {
File exclFile = new File(excl).getAbsoluteFile();
String base = exclFile.getParent();
for (String pattern : NEWLINE.split(new WholeIO().strictread(exclFile)))
addPathPattern(excludes, base, pattern);
}
this.excludeMatcher = new PathMatcher(excludes);
if (ap.has(P_DEBUG_EXCLUSIONS)) {
System.out.println("Inclusion patterns: " + this.includeMatcher);
System.out.println("Exclusion patterns: " + this.excludeMatcher);
}
}
private void addIncludesFor(Set<String> includes, FileType filetype) {
for (String extension : filetype.getExtensions()) includes.add("**/*" + extension);
}
private void addPathPattern(Set<String> patterns, String base, String pattern) {
pattern = pattern.trim();
if (pattern.isEmpty()) return;
if (!FileUtil.isAbsolute(pattern) && base != null) {
pattern = base + "/" + pattern;
}
if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length() - 1);
patterns.add(pattern);
}
private ArgsParser addArgs(ArgsParser argsParser) {
argsParser.addDeprecatedFlag(
P_ECMA_VERSION, 1, "Files are now always extracted as ECMAScript 2017.");
argsParser.addFlag(
P_EXCLUDE, 1, "Do not extract files matching the given filename pattern.", true);
argsParser.addToleratedFlag(P_EXCLUDE_PATH, 1, true);
argsParser.addFlag(
P_EXPERIMENTAL,
0,
"Enable experimental support for pending ECMAScript proposals "
+ "(public class fields, function.sent, decorators, export extensions, function bind, "
+ "parameter-less catch, dynamic import, numeric separators, bigints, top-level await), "
+ "as well as other language extensions (E4X, JScript, Mozilla and v8-specific extensions) and full HTML extraction.");
argsParser.addFlag(
P_EXTERNS, 0, "Extract the given JavaScript files as Closure-style externs.");
argsParser.addFlag(
P_EXTRACT_PROGRAM_TEXT,
0,
"Extract a representation of the textual content of the program "
+ "(in addition to its syntactic structure).");
argsParser.addFlag(
P_FILE_TYPE,
1,
"Assume all files to be of the given type, regardless of extension; "
+ "the type must be one of "
+ StringUtil.glue(", ", FileExtractor.FileType.allNames)
+ ".");
argsParser.addFlag(P_HELP, 0, "Display this help.");
argsParser.addFlag(
P_HTML,
1,
"Control extraction of HTML files: "
+ "'scripts' extracts JavaScript code embedded inside HTML, but not the HTML itself; "
+ "'elements' additionally extracts HTML elements and their attributes, as well as HTML comments, but not textual content (default); "
+ "'all' extracts elements, embedded scripts, comments and text.");
argsParser.addFlag(
P_INCLUDE,
1,
"Extract files matching the given filename pattern (in addition to HTML and JavaScript files).",
true);
argsParser.addDeprecatedFlag(P_JSCRIPT, 0, "Use '" + P_EXPERIMENTAL + "' instead.");
argsParser.addDeprecatedFlag(P_MOZ_EXTENSIONS, 0, "Use '" + P_EXPERIMENTAL + "' instead.");
argsParser.addDeprecatedFlag(P_NODEJS, 0, "Use '" + P_PLATFORM + " node' instead.");
argsParser.addFlag(
P_PLATFORM,
1,
"Extract the given JavaScript files as code for the given platform: "
+ "'node' extracts them as Node.js modules; "
+ "'web' as plain JavaScript files; "
+ "'auto' uses heuristics to automatically detect "
+ "Node.js modules and extracts everything else as plain JavaScript files. "
+ "The default is 'auto'.");
argsParser.addFlag(P_QUIET, 0, "Produce less output.");
argsParser.addFlag(
P_SOURCE_TYPE,
1,
"The source type to use; must be one of 'script', 'module' or 'auto'. "
+ "The default is 'auto'.");
argsParser.addToleratedFlag(P_TOLERATE_PARSE_ERRORS, 0);
argsParser.addFlag(
P_ABORT_ON_PARSE_ERRORS, 0, "Abort extraction if a parse error is encountered.");
argsParser.addFlag(P_TRAP_CACHE, 1, "Use the given directory as the TRAP cache.");
argsParser.addFlag(
P_TRAP_CACHE_BOUND,
1,
"A (soft) upper limit on the size of the TRAP cache, "
+ "in standard size units (e.g., 'g' for gigabytes).");
argsParser.addFlag(P_DEFAULT_ENCODING, 1, "The encoding to use; default is UTF-8.");
argsParser.addFlag(P_TYPESCRIPT, 0, "Enable basic TypesScript support.");
argsParser.addFlag(
P_TYPESCRIPT_FULL, 0, "Enable full TypeScript support with static type information.");
argsParser.addFlag(
P_TYPESCRIPT_RAM,
1,
"Amount of memory allocated to the TypeScript compiler process. The default is 1G.");
argsParser.addToleratedFlag(P_DEBUG_EXCLUSIONS, 0);
argsParser.addTrailingParam("files", "Files and directories to extract.");
return argsParser;
}
private boolean enableExperimental(ArgsParser ap) {
return ap.has(P_EXPERIMENTAL) || ap.has(P_JSCRIPT) || ap.has(P_MOZ_EXTENSIONS);
}
private static TypeScriptMode getTypeScriptMode(ArgsParser ap) {
if (ap.has(P_TYPESCRIPT_FULL)) return TypeScriptMode.FULL;
if (ap.has(P_TYPESCRIPT)) return TypeScriptMode.BASIC;
return TypeScriptMode.NONE;
}
private Path inferSourceRoot(ArgsParser ap) {
List<File> files = getFilesArg(ap);
Path sourceRoot = files.iterator().next().toPath().toAbsolutePath().getParent();
for (File file : files) {
Path path = file.toPath().toAbsolutePath().getParent();
for (int i = 0; i < sourceRoot.getNameCount(); ++i) {
if (!(i < path.getNameCount() && path.getName(i).equals(sourceRoot.getName(i)))) {
sourceRoot = sourceRoot.subpath(0, i);
break;
}
}
}
return sourceRoot;
}
private ExtractorConfig parseJSOptions(ArgsParser ap) {
ExtractorConfig cfg =
new ExtractorConfig(enableExperimental(ap))
.withExterns(ap.has(P_EXTERNS))
.withPlatform(getPlatform(ap))
.withTolerateParseErrors(
ap.has(P_TOLERATE_PARSE_ERRORS) || !ap.has(P_ABORT_ON_PARSE_ERRORS))
.withHtmlHandling(
ap.getEnum(
P_HTML,
HTMLHandling.class,
ap.has(P_EXPERIMENTAL) ? HTMLHandling.ALL : HTMLHandling.ELEMENTS))
.withFileType(getFileType(ap))
.withSourceType(ap.getEnum(P_SOURCE_TYPE, SourceType.class, SourceType.AUTO))
.withExtractLines(ap.has(P_EXTRACT_PROGRAM_TEXT))
.withTypeScriptMode(getTypeScriptMode(ap))
.withTypeScriptRam(
ap.has(P_TYPESCRIPT_RAM)
? UnitParser.parseOpt(ap.getString(P_TYPESCRIPT_RAM), UnitParser.MEGABYTES)
: 0);
if (ap.has(P_DEFAULT_ENCODING)) cfg = cfg.withDefaultEncoding(ap.getString(P_DEFAULT_ENCODING));
// Make a usable virtual source root mapping.
// The concept of source root and scratch directory do not exist in the legacy extractor,
// so we construct these based on what we have.
String odasaDbDir = Env.systemEnv().getNonEmpty(Var.ODASA_DB);
VirtualSourceRoot virtualSourceRoot =
odasaDbDir == null
? VirtualSourceRoot.none
: new VirtualSourceRoot(inferSourceRoot(ap), Paths.get(odasaDbDir, "working"));
cfg = cfg.withVirtualSourceRoot(virtualSourceRoot);
return cfg;
}
private String getFileType(ArgsParser ap) {
String fileType = null;
if (ap.has(P_FILE_TYPE)) {
fileType = StringUtil.uc(ap.getString(P_FILE_TYPE));
if (!FileExtractor.FileType.allNames.contains(fileType))
ap.error("Invalid file type " + ap.getString(P_FILE_TYPE));
}
return fileType;
}
private Platform getPlatform(ArgsParser ap) {
if (ap.has(P_NODEJS)) return Platform.NODE;
return ap.getEnum(P_PLATFORM, Platform.class, Platform.AUTO);
}
/**
* Collect files to extract under a given root, which may be either a file or a directory. The
* {@code explicit} flag indicates whether {@code root} was explicitly passed to the extractor as
* a command line argument, or whether it is examined as part of a recursive traversal.
*/
private void collectFiles(File root, boolean explicit) {
if (!root.exists()) {
System.err.println("Skipping " + root + ", which does not exist.");
return;
}
if (root.isDirectory()) {
// exclude directories we've seen before
if (seenDirectories.add(FileUtil.tryMakeCanonical(root).getPath()))
// apply exclusion filters for directories
if (!excludeMatcher.matches(root.getAbsolutePath())) {
File[] gs = root.listFiles();
if (gs == null) System.err.println("Skipping " + root + ", which cannot be listed.");
else for (File g : gs) collectFiles(g, false);
}
} else {
String path = root.getAbsolutePath();
// extract files that are supported, match the layout (if any), pass the includeMatcher,
// and do not pass the excludeMatcher
if (fileExtractor.supports(root)
&& extractorOutputConfig.shouldExtract(root)
&& (explicit || includeMatcher.matches(path) && !excludeMatcher.matches(path))) {
files.add(normalizeFile(root));
}
if (extractorConfig.getTypeScriptMode() == TypeScriptMode.FULL
&& root.getName().equals("tsconfig.json")
&& !excludeMatcher.matches(path)) {
projectFiles.add(root);
}
}
}
private File normalizeFile(File root) {
return root.getAbsoluteFile().toPath().normalize().toFile();
}
public static void main(String[] args) {
try {
new Main(new ExtractorOutputConfig(LegacyLanguage.JAVASCRIPT)).run(args);
} catch (UserError e) {
System.err.println(e.getMessage());
if (!e.reportAsInfoMessage()) System.exit(1);
}
}
}
| 23,375 | 39.234079 | 146 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/RegExpExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.SourceElement;
import com.semmle.js.ast.regexp.BackReference;
import com.semmle.js.ast.regexp.Caret;
import com.semmle.js.ast.regexp.CharacterClass;
import com.semmle.js.ast.regexp.CharacterClassEscape;
import com.semmle.js.ast.regexp.CharacterClassRange;
import com.semmle.js.ast.regexp.Constant;
import com.semmle.js.ast.regexp.ControlEscape;
import com.semmle.js.ast.regexp.ControlLetter;
import com.semmle.js.ast.regexp.DecimalEscape;
import com.semmle.js.ast.regexp.Disjunction;
import com.semmle.js.ast.regexp.Dollar;
import com.semmle.js.ast.regexp.Dot;
import com.semmle.js.ast.regexp.Error;
import com.semmle.js.ast.regexp.Group;
import com.semmle.js.ast.regexp.HexEscapeSequence;
import com.semmle.js.ast.regexp.IdentityEscape;
import com.semmle.js.ast.regexp.Literal;
import com.semmle.js.ast.regexp.NamedBackReference;
import com.semmle.js.ast.regexp.NonWordBoundary;
import com.semmle.js.ast.regexp.OctalEscape;
import com.semmle.js.ast.regexp.Opt;
import com.semmle.js.ast.regexp.Plus;
import com.semmle.js.ast.regexp.Quantifier;
import com.semmle.js.ast.regexp.Range;
import com.semmle.js.ast.regexp.RegExpTerm;
import com.semmle.js.ast.regexp.Sequence;
import com.semmle.js.ast.regexp.Star;
import com.semmle.js.ast.regexp.UnicodeEscapeSequence;
import com.semmle.js.ast.regexp.UnicodePropertyEscape;
import com.semmle.js.ast.regexp.Visitor;
import com.semmle.js.ast.regexp.WordBoundary;
import com.semmle.js.ast.regexp.ZeroWidthNegativeLookahead;
import com.semmle.js.ast.regexp.ZeroWidthNegativeLookbehind;
import com.semmle.js.ast.regexp.ZeroWidthPositiveLookahead;
import com.semmle.js.ast.regexp.ZeroWidthPositiveLookbehind;
import com.semmle.js.parser.RegExpParser;
import com.semmle.js.parser.RegExpParser.Result;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.LinkedHashMap;
import java.util.Map;
/** Extractor for populating regular expressions. */
public class RegExpExtractor {
private final TrapWriter trapwriter;
private final LocationManager locationManager;
private final RegExpParser parser = new RegExpParser();
private Position literalStart;
private OffsetTranslation offsets;
public RegExpExtractor(TrapWriter trapwriter, LocationManager locationManager) {
this.trapwriter = trapwriter;
this.locationManager = locationManager;
}
private static final Map<String, Integer> termkinds = new LinkedHashMap<String, Integer>();
static {
termkinds.put("Disjunction", 0);
termkinds.put("Sequence", 1);
termkinds.put("Caret", 2);
termkinds.put("Dollar", 3);
termkinds.put("WordBoundary", 4);
termkinds.put("NonWordBoundary", 5);
termkinds.put("ZeroWidthPositiveLookahead", 6);
termkinds.put("ZeroWidthNegativeLookahead", 7);
termkinds.put("Star", 8);
termkinds.put("Plus", 9);
termkinds.put("Opt", 10);
termkinds.put("Range", 11);
termkinds.put("Dot", 12);
termkinds.put("Group", 13);
termkinds.put("Constant", 14);
termkinds.put("HexEscapeSequence", 15);
termkinds.put("UnicodeEscapeSequence", 16);
termkinds.put("DecimalEscape", 17);
termkinds.put("OctalEscape", 18);
termkinds.put("ControlEscape", 19);
termkinds.put("ControlLetter", 19); // not a typo; these two are merged in the database
termkinds.put("CharacterClassEscape", 20);
termkinds.put("IdentityEscape", 21);
termkinds.put("BackReference", 22);
termkinds.put("CharacterClass", 23);
termkinds.put("CharacterClassRange", 24);
termkinds.put("NamedBackReference", 22); // merged with BackReference in the database
termkinds.put("ZeroWidthPositiveLookbehind", 25);
termkinds.put("ZeroWidthNegativeLookbehind", 26);
termkinds.put("UnicodePropertyEscape", 27);
}
private static final String[] errmsgs =
new String[] {
"unexpected end of regular expression",
"unexpected character",
"expected digit",
"expected hexadecimal digit",
"expected control letter",
"expected ')'",
"expected '}'",
"trailing characters",
"octal escape sequence",
"invalid back reference",
"expected ']'",
"expected identifier",
"expected '>'"
};
private Label extractTerm(RegExpTerm term, Label parent, int idx) {
Label lbl = trapwriter.localID(term);
int kind = termkinds.get(term.getType());
String srctext = term.getLoc().getSource();
this.trapwriter.addTuple("regexpterm", lbl, kind, parent, idx, srctext);
emitLocation(term, lbl);
return lbl;
}
public void emitLocation(SourceElement term, Label lbl) {
int col = literalStart.getColumn();
int sl, sc, el, ec;
sl = el = literalStart.getLine();
sc = col + offsets.get(term.getLoc().getStart().getColumn());
ec = col + offsets.get(term.getLoc().getEnd().getColumn());
sc += 1; // convert to 1-based
ec += 1; // convert to 1-based
ec -= 1; // convert to inclusive
locationManager.emitSnippetLocation(lbl, sl, sc, el, ec);
}
private class V implements Visitor {
private Label parent;
private int idx;
private void visit(RegExpTerm child, Label parent, int idx) {
Label oldParent = this.parent;
int oldIdx = this.idx;
this.parent = parent;
this.idx = idx;
child.accept(this);
this.parent = oldParent;
this.idx = oldIdx;
}
@Override
public void visit(BackReference nd) {
Label lbl = extractTerm(nd, parent, idx);
if (inRange(nd.getValue())) trapwriter.addTuple("backref", lbl, nd.getValue());
}
@Override
public void visit(NamedBackReference nd) {
Label lbl = extractTerm(nd, parent, idx);
trapwriter.addTuple("namedBackref", lbl, nd.getName());
}
@Override
public void visit(Caret nd) {
extractTerm(nd, parent, idx);
}
@Override
public void visit(Dot nd) {
extractTerm(nd, parent, idx);
}
@Override
public void visit(Constant nd) {
visit((Literal) nd);
}
@Override
public void visit(Dollar nd) {
extractTerm(nd, parent, idx);
}
@Override
public void visit(Group nd) {
Label lbl = extractTerm(nd, parent, idx);
if (nd.isCapture()) trapwriter.addTuple("isCapture", lbl, nd.getNumber());
if (nd.isNamed()) trapwriter.addTuple("isNamedCapture", lbl, nd.getName());
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(ZeroWidthPositiveLookahead nd) {
Label lbl = extractTerm(nd, parent, idx);
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(ZeroWidthNegativeLookahead nd) {
Label lbl = extractTerm(nd, parent, idx);
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(ZeroWidthPositiveLookbehind nd) {
Label lbl = extractTerm(nd, parent, idx);
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(ZeroWidthNegativeLookbehind nd) {
Label lbl = extractTerm(nd, parent, idx);
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(NonWordBoundary nd) {
extractTerm(nd, parent, idx);
}
private void visit(Quantifier nd) {
Label lbl = extractTerm(nd, parent, idx);
if (nd.isGreedy()) trapwriter.addTuple("isGreedy", lbl);
visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(Opt nd) {
visit((Quantifier) nd);
}
@Override
public void visit(Plus nd) {
visit((Quantifier) nd);
}
private boolean inRange(long l) {
return 0 <= l && l <= Integer.MAX_VALUE;
}
@Override
public void visit(Range nd) {
Label lbl = extractTerm(nd, parent, idx);
if (nd.isGreedy()) trapwriter.addTuple("isGreedy", lbl);
long lo = nd.getLowerBound();
if (inRange(lo)) trapwriter.addTuple("rangeQuantifierLowerBound", lbl, lo);
if (nd.hasUpperBound()) {
long hi = nd.getUpperBound();
if (inRange(hi)) trapwriter.addTuple("rangeQuantifierUpperBound", lbl, hi);
}
this.visit(nd.getOperand(), lbl, 0);
}
@Override
public void visit(Sequence nd) {
Label lbl = extractTerm(nd, parent, idx);
int i = 0;
for (RegExpTerm element : nd.getElements()) visit(element, lbl, i++);
}
@Override
public void visit(Disjunction nd) {
Label lbl = extractTerm(nd, parent, idx);
int i = 0;
for (RegExpTerm element : nd.getDisjuncts()) visit(element, lbl, i++);
}
@Override
public void visit(Star nd) {
visit((Quantifier) nd);
}
@Override
public void visit(WordBoundary nd) {
extractTerm(nd, parent, idx);
}
@Override
public void visit(CharacterClassEscape nd) {
Label lbl = extractTerm(nd, parent, idx);
trapwriter.addTuple("charClassEscape", lbl, nd.getClassIdentifier());
}
@Override
public void visit(UnicodePropertyEscape nd) {
Label lbl = extractTerm(nd, parent, idx);
trapwriter.addTuple("unicodePropertyEscapeName", lbl, nd.getName());
if (nd.hasValue()) trapwriter.addTuple("unicodePropertyEscapeValue", lbl, nd.getValue());
}
@Override
public void visit(DecimalEscape nd) {
visit((Literal) nd);
}
private void visit(Literal nd) {
Label lbl = extractTerm(nd, parent, idx);
trapwriter.addTuple("regexpConstValue", lbl, nd.getValue());
}
@Override
public void visit(HexEscapeSequence nd) {
visit((Literal) nd);
}
@Override
public void visit(OctalEscape nd) {
visit((Literal) nd);
}
@Override
public void visit(UnicodeEscapeSequence nd) {
visit((Literal) nd);
}
@Override
public void visit(ControlEscape nd) {
visit((Literal) nd);
}
@Override
public void visit(ControlLetter nd) {
visit((Literal) nd);
}
@Override
public void visit(IdentityEscape nd) {
visit((Literal) nd);
}
@Override
public void visit(CharacterClass nd) {
Label lbl = extractTerm(nd, parent, idx);
if (nd.isInverted()) trapwriter.addTuple("isInverted", lbl);
int i = 0;
for (RegExpTerm element : nd.getElements()) visit(element, lbl, i++);
}
@Override
public void visit(CharacterClassRange nd) {
Label lbl = extractTerm(nd, parent, idx);
visit(nd.getLeft(), lbl, 0);
visit(nd.getRight(), lbl, 1);
}
}
public void extract(
String src, OffsetTranslation offsets, Node parent, boolean isSpeculativeParsing) {
Result res = parser.parse(src);
if (isSpeculativeParsing && res.getErrors().size() > 0) {
return;
}
this.literalStart = parent.getLoc().getStart();
this.offsets = offsets;
RegExpTerm ast = res.getAST();
new V().visit(ast, trapwriter.localID(parent), 0);
Label rootLbl = trapwriter.localID(ast);
for (Error err : res.getErrors()) {
Label lbl = this.trapwriter.freshLabel();
String msg = errmsgs[err.getCode()];
this.trapwriter.addTuple("regexpParseErrors", lbl, rootLbl, msg);
this.emitLocation(err, lbl);
}
}
}
| 11,281 | 29.409704 | 95 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/JSExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.Comment;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.Token;
import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase;
import com.semmle.js.extractor.ExtractorConfig.ECMAVersion;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.parser.JSParser;
import com.semmle.js.parser.ParseError;
import com.semmle.util.data.Pair;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.exception.UserError;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Extractor for populating JavaScript source code, including AST information, lexical information
* about comments and tokens, textual information about lines, control flow graphs, and JSDoc
* comments.
*/
public class JSExtractor {
private final ExtractorConfig config;
public JSExtractor(ExtractorConfig config) {
this.config = config;
}
// heuristic: if `import`, `export`, or `goog.module` appears at the beginning of a line, it's
// probably a module
private static final Pattern containsModuleIndicator =
Pattern.compile("(?m)^([ \t]*)(import|export|goog\\.module)\\b");
public Pair<Label, LoCInfo> extract(
TextualExtractor textualExtractor, String source, int toplevelKind, ScopeManager scopeManager)
throws ParseError {
// if the file starts with `{ "<string>":` it won't parse as JavaScript; try parsing as JSON
// instead
if (FileExtractor.JSON_OBJECT_START.matcher(textualExtractor.getSource()).matches()) {
try {
LoCInfo loc =
new JSONExtractor(config.withTolerateParseErrors(false)).extract(textualExtractor);
return Pair.make(null, loc);
} catch (UserError ue) {
// didn't work, so parse as JavaScript (and fail)
Exceptions.ignore(ue, "Try parsing as JavaScript instead.");
}
}
SourceType sourceType = establishSourceType(source, true);
JSParser.Result parserRes =
JSParser.parse(config, sourceType, source, textualExtractor.getMetrics());
return extract(textualExtractor, source, toplevelKind, scopeManager, sourceType, parserRes);
}
/**
* Determine the {@link SourceType} of {@code source}.
*
* <p>If the configuration specifies as explicit source type, we use that. Otherwise, for
* ECMAScript 2015 and greater we check for lines starting with {@code import} or {@code export},
* and if we find any we assume it's a module. For plain JavaScript, we allow leading whitespace
* before the {@code import}/ {@code export}, but not for TypeScript, to avoid getting confused by
* namespace exports.
*
* <p>If all else fails, we go with {@link SourceType#SCRIPT}.
*/
public SourceType establishSourceType(String source, boolean allowLeadingWS) {
SourceType sourceType = config.getSourceType();
if (sourceType != SourceType.AUTO) return sourceType;
if (config.getEcmaVersion().compareTo(ECMAVersion.ECMA2015) >= 0) {
Matcher m = containsModuleIndicator.matcher(source);
if (m.find() && (allowLeadingWS || m.group(1).isEmpty())) {
return m.group(2).startsWith("goog") ? SourceType.CLOSURE_MODULE : SourceType.MODULE;
}
}
return SourceType.SCRIPT;
}
public Pair<Label, LoCInfo> extract(
TextualExtractor textualExtractor,
String source,
int toplevelKind,
ScopeManager scopeManager,
SourceType sourceType,
JSParser.Result parserRes)
throws ParseError {
textualExtractor.getMetrics().startPhase(ExtractionPhase.JSExtractor_extract);
Label toplevelLabel;
TrapWriter trapwriter = textualExtractor.getTrapwriter();
LocationManager locationManager = textualExtractor.getLocationManager();
Platform platform = config.getPlatform();
Node ast = parserRes.getAST();
LexicalExtractor lexicalExtractor;
LoCInfo loc;
if (ast != null) {
platform = getPlatform(platform, ast);
if (sourceType == SourceType.SCRIPT && platform == Platform.NODE) {
sourceType = SourceType.COMMONJS_MODULE;
}
lexicalExtractor =
new LexicalExtractor(textualExtractor, parserRes.getTokens(), parserRes.getComments());
ASTExtractor scriptExtractor = new ASTExtractor(lexicalExtractor, scopeManager);
toplevelLabel = scriptExtractor.getToplevelLabel();
lexicalExtractor.extractComments(toplevelLabel);
loc = lexicalExtractor.extractLines(parserRes.getSource(), toplevelLabel);
lexicalExtractor.extractTokens(toplevelLabel);
new JSDocExtractor(textualExtractor).extract(lexicalExtractor.getComments());
lexicalExtractor.purge();
parserRes.getErrors().addAll(scriptExtractor.extract(ast, platform, sourceType, toplevelKind));
new CFGExtractor(scriptExtractor).extract(ast);
} else {
lexicalExtractor =
new LexicalExtractor(textualExtractor, new ArrayList<Token>(), new ArrayList<Comment>());
ASTExtractor scriptExtractor = new ASTExtractor(lexicalExtractor, null);
toplevelLabel = scriptExtractor.getToplevelLabel();
trapwriter.addTuple("toplevels", toplevelLabel, toplevelKind);
locationManager.emitSnippetLocation(toplevelLabel, 1, 1, 1, 1);
loc = new LoCInfo(0, 0);
}
for (ParseError parseError : parserRes.getErrors()) {
if (!config.isTolerateParseErrors()) throw parseError;
Label key = trapwriter.freshLabel();
String errorLine = textualExtractor.getLine(parseError.getPosition().getLine());
trapwriter.addTuple("jsParseErrors", key, toplevelLabel, "Error: " + parseError, errorLine);
locationManager.emitErrorLocation(
key, parseError.getPosition(), textualExtractor.getNumLines());
lexicalExtractor.extractLines(source, toplevelLabel);
}
if (config.isExterns()) textualExtractor.getTrapwriter().addTuple("isExterns", toplevelLabel);
if (platform == Platform.NODE && sourceType == SourceType.COMMONJS_MODULE)
textualExtractor.getTrapwriter().addTuple("isNodejs", toplevelLabel);
textualExtractor.getMetrics().stopPhase(ExtractionPhase.JSExtractor_extract);
return Pair.make(toplevelLabel, loc);
}
private Platform getPlatform(Platform platform, Node ast) {
if (platform == Platform.AUTO)
return NodeJSDetector.looksLikeNodeJS(ast) ? Platform.NODE : Platform.WEB;
return platform;
}
}
| 6,578 | 41.445161 | 101 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/JSDocExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.Comment;
import com.semmle.js.ast.jsdoc.AllLiteral;
import com.semmle.js.ast.jsdoc.ArrayType;
import com.semmle.js.ast.jsdoc.FieldType;
import com.semmle.js.ast.jsdoc.FunctionType;
import com.semmle.js.ast.jsdoc.JSDocComment;
import com.semmle.js.ast.jsdoc.JSDocElement;
import com.semmle.js.ast.jsdoc.JSDocTag;
import com.semmle.js.ast.jsdoc.JSDocTypeExpression;
import com.semmle.js.ast.jsdoc.NameExpression;
import com.semmle.js.ast.jsdoc.NonNullableType;
import com.semmle.js.ast.jsdoc.NullLiteral;
import com.semmle.js.ast.jsdoc.NullableLiteral;
import com.semmle.js.ast.jsdoc.NullableType;
import com.semmle.js.ast.jsdoc.OptionalType;
import com.semmle.js.ast.jsdoc.ParameterType;
import com.semmle.js.ast.jsdoc.RecordType;
import com.semmle.js.ast.jsdoc.RestType;
import com.semmle.js.ast.jsdoc.TypeApplication;
import com.semmle.js.ast.jsdoc.UnaryTypeConstructor;
import com.semmle.js.ast.jsdoc.UndefinedLiteral;
import com.semmle.js.ast.jsdoc.UnionType;
import com.semmle.js.ast.jsdoc.Visitor;
import com.semmle.js.ast.jsdoc.VoidLiteral;
import com.semmle.js.parser.JSDocParser;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Extractor for populating JSDoc comments. */
public class JSDocExtractor {
private static final Map<String, Integer> jsdocTypeExprKinds =
new LinkedHashMap<String, Integer>();
static {
jsdocTypeExprKinds.put("AllLiteral", 0);
jsdocTypeExprKinds.put("NullLiteral", 1);
jsdocTypeExprKinds.put("UndefinedLiteral", 2);
jsdocTypeExprKinds.put("NullableLiteral", 3);
jsdocTypeExprKinds.put("VoidLiteral", 4);
jsdocTypeExprKinds.put("NameExpression", 5);
jsdocTypeExprKinds.put("TypeApplication", 6);
jsdocTypeExprKinds.put("NullableType", 7);
jsdocTypeExprKinds.put("NonNullableType", 8);
jsdocTypeExprKinds.put("RecordType", 9);
jsdocTypeExprKinds.put("ArrayType", 10);
jsdocTypeExprKinds.put("UnionType", 11);
jsdocTypeExprKinds.put("FunctionType", 12);
jsdocTypeExprKinds.put("OptionalType", 13);
jsdocTypeExprKinds.put("RestType", 14);
}
private final TrapWriter trapwriter;
private final LocationManager locationManager;
public JSDocExtractor(TextualExtractor textualExtractor) {
this.trapwriter = textualExtractor.getTrapwriter();
this.locationManager = textualExtractor.getLocationManager();
}
private class V implements Visitor {
private Label parent;
private int idx;
private Label visit(JSDocTypeExpression nd) {
Label key = trapwriter.localID(nd);
int kind = jsdocTypeExprKinds.get(nd.getType());
trapwriter.addTuple("jsdoc_type_exprs", key, kind, parent, idx, nd.pp());
locationManager.emitNodeLocation(nd, key);
return key;
}
public void visit(Label parent, List<? extends JSDocElement> nds) {
Label oldParent = this.parent;
int oldIdx = this.idx;
this.parent = parent;
this.idx = 0;
for (JSDocElement element : nds) {
element.accept(this);
++this.idx;
}
this.parent = oldParent;
this.idx = oldIdx;
}
public void visit(JSDocElement child, Label parent, int idx) {
if (child == null) return;
Label oldParent = this.parent;
int oldIdx = this.idx;
this.parent = parent;
this.idx = idx;
child.accept(this);
this.parent = oldParent;
this.idx = oldIdx;
}
@Override
public void visit(AllLiteral nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(FieldType nd) {
trapwriter.addTuple("jsdoc_record_field_name", parent, idx, nd.getKey());
if (nd.hasValue()) visit(nd.getValue(), parent, idx);
}
@Override
public void visit(RecordType nd) {
Label label = visit((JSDocTypeExpression) nd);
visit(label, nd.getFields());
}
@Override
public void visit(NameExpression nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(NullableLiteral nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(NullLiteral nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(UndefinedLiteral nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(VoidLiteral nd) {
visit((JSDocTypeExpression) nd);
}
@Override
public void visit(JSDocComment nd) {
Label commentLabel = trapwriter.localID(nd.getComment());
Label jsdocLabel = trapwriter.freshLabel();
trapwriter.addTuple("jsdoc", jsdocLabel, nd.getDescription(), commentLabel);
locationManager.emitNodeLocation(nd, jsdocLabel);
visit(jsdocLabel, nd.getTags());
}
@Override
public void visit(JSDocTag nd) {
Label label = trapwriter.localID(nd);
trapwriter.addTuple("jsdoc_tags", label, nd.getTitle(), parent, idx, "@" + nd.getTitle());
locationManager.emitNodeLocation(nd, label);
if (nd.hasDescription() && !nd.getDescription().isEmpty())
trapwriter.addTuple("jsdoc_tag_descriptions", label, nd.getDescription());
if (nd.hasName()) trapwriter.addTuple("jsdoc_tag_names", label, nd.getName());
visit(nd.getType(), label, 0);
for (String msg : nd.getErrors())
trapwriter.addTuple(
"jsdoc_errors",
trapwriter.freshLabel(),
label,
msg,
TextualExtractor.sanitiseToString(msg));
}
@Override
public void visit(UnionType nd) {
Label label = visit((JSDocTypeExpression) nd);
List<JSDocTypeExpression> elements = nd.getElements();
visit(label, elements);
}
@Override
public void visit(ArrayType nd) {
Label label = visit((JSDocTypeExpression) nd);
List<JSDocTypeExpression> elements = nd.getElements();
visit(label, elements);
}
@Override
public void visit(TypeApplication nd) {
Label label = visit((JSDocTypeExpression) nd);
visit(nd.getExpression(), label, -1);
visit(label, nd.getApplications());
}
@Override
public void visit(FunctionType nd) {
Label label = visit((JSDocTypeExpression) nd);
visit(label, nd.getParams());
visit(nd.getResult(), label, -1);
visit(nd.getThis(), label, -2);
if (nd.isNew()) trapwriter.addTuple("jsdoc_has_new_parameter", label);
}
@Override
public void visit(ParameterType nd) {
visit(nd.getExpression(), parent, idx);
}
private void visit(UnaryTypeConstructor nd) {
Label label = visit((JSDocTypeExpression) nd);
visit(nd.getExpression(), label, 0);
if (!(nd instanceof RestType) && nd.isPrefix())
trapwriter.addTuple("jsdoc_prefix_qualifier", label);
}
@Override
public void visit(NonNullableType nd) {
visit((UnaryTypeConstructor) nd);
}
@Override
public void visit(NullableType nd) {
visit((UnaryTypeConstructor) nd);
}
@Override
public void visit(OptionalType nd) {
visit((UnaryTypeConstructor) nd);
}
@Override
public void visit(RestType nd) {
visit((UnaryTypeConstructor) nd);
}
}
public void extract(List<Comment> comments) {
JSDocParser jsdocParser = new JSDocParser();
for (Comment comment : comments) {
if (comment.isDocComment()) {
JSDocComment docComment = jsdocParser.parse(comment);
docComment.accept(new V());
}
}
}
}
| 7,602 | 29.170635 | 96 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/NodeJSDetector.java | package com.semmle.js.extractor;
import com.semmle.js.ast.AssignmentExpression;
import com.semmle.js.ast.BlockStatement;
import com.semmle.js.ast.CallExpression;
import com.semmle.js.ast.Expression;
import com.semmle.js.ast.ExpressionStatement;
import com.semmle.js.ast.IFunction;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.IfStatement;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.ParenthesizedExpression;
import com.semmle.js.ast.Program;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.TryStatement;
import com.semmle.js.ast.UnaryExpression;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.js.ast.VariableDeclarator;
import java.util.List;
/** A utility class for detecting Node.js code. */
public class NodeJSDetector {
/**
* Is {@code ast} a program that looks like Node.js code, that is, does it contain a top-level
* {@code require} or an export?
*/
public static boolean looksLikeNodeJS(Node ast) {
if (!(ast instanceof Program)) return false;
return hasToplevelRequireOrExport(((Program) ast).getBody());
}
/**
* Does this program contain a statement that looks like a Node.js {@code require} or an export?
*
* <p>We recursively traverse argument-less immediately invoked function expressions (i.e., no UMD
* modules), but not loops or if statements.
*/
private static boolean hasToplevelRequireOrExport(List<Statement> stmts) {
for (Statement stmt : stmts) if (hasToplevelRequireOrExport(stmt)) return true;
return false;
}
private static boolean hasToplevelRequireOrExport(Statement stmt) {
if (stmt instanceof ExpressionStatement) {
Expression e = stripParens(((ExpressionStatement) stmt).getExpression());
// check whether `e` is an iife; if so, recursively check its body
// strip off unary operators to handle `!function(){...}()`
if (e instanceof UnaryExpression) e = ((UnaryExpression) e).getArgument();
if (e instanceof CallExpression && ((CallExpression) e).getArguments().isEmpty()) {
Expression callee = stripParens(((CallExpression) e).getCallee());
if (callee instanceof IFunction) {
Node body = ((IFunction) callee).getBody();
if (body instanceof BlockStatement)
return hasToplevelRequireOrExport(((BlockStatement) body).getBody());
}
}
if (isRequireCall(e) || isExport(e)) return true;
} else if (stmt instanceof VariableDeclaration) {
for (VariableDeclarator decl : ((VariableDeclaration) stmt).getDeclarations()) {
Expression init = stripParens(decl.getInit());
if (isRequireCall(init) || isExport(init)) return true;
}
} else if (stmt instanceof TryStatement) {
return hasToplevelRequireOrExport(((TryStatement) stmt).getBlock());
} else if (stmt instanceof BlockStatement) {
return hasToplevelRequireOrExport(((BlockStatement) stmt).getBody());
} else if (stmt instanceof IfStatement) {
IfStatement is = (IfStatement) stmt;
return hasToplevelRequireOrExport(is.getConsequent())
|| hasToplevelRequireOrExport(is.getAlternate());
}
return false;
}
private static Expression stripParens(Expression e) {
if (e instanceof ParenthesizedExpression)
return stripParens(((ParenthesizedExpression) e).getExpression());
return e;
}
/**
* Is {@code e} a call to a function named {@code require} with one argument, or an assignment
* whose right hand side is the result of such a call?
*/
private static boolean isRequireCall(Expression e) {
if (e instanceof CallExpression) {
CallExpression call = (CallExpression) e;
Expression callee = call.getCallee();
if (isIdentifier(callee, "require") && call.getArguments().size() == 1) return true;
if (isRequireCall(callee)) return true;
return false;
} else if (e instanceof MemberExpression) {
return isRequireCall(((MemberExpression) e).getObject());
} else if (e instanceof AssignmentExpression) {
AssignmentExpression assgn = (AssignmentExpression) e;
// filter out compound assignments
if (!"=".equals(assgn.getOperator())) return false;
return isRequireCall(assgn.getRight());
}
return false;
}
/**
* Does {@code e} look like a Node.js export?
*
* <p>Currently, three kinds of exports are recognised:
*
* <ul>
* <li><code>exports.foo = ...</code>
* <li><code>module.exports = ...</code>
* <li><code>module.exports.foo = ...</code>
* </ul>
*
* Detection is done recursively, so <code>foo = exports.foo = ...</code> is handled correctly.
*/
private static boolean isExport(Expression e) {
if (e instanceof AssignmentExpression) {
AssignmentExpression assgn = (AssignmentExpression) e;
// filter out compound assignments
if (!"=".equals(assgn.getOperator())) return false;
if (assgn.getLeft() instanceof MemberExpression) {
MemberExpression target = (MemberExpression) assgn.getLeft();
// `exports.foo = ...;`
if (isIdentifier(target.getObject(), "exports")) return true;
// `module.exports = ...;`
if (isModuleExports(target)) return true;
if (target.getObject() instanceof MemberExpression) {
MemberExpression targetBase = (MemberExpression) target.getObject();
// `module.exports.foo = ...;`
if (isModuleExports(targetBase)) return true;
}
}
// recursively check right hand side
return isExport(assgn.getRight());
}
return false;
}
/** Is {@code me} a member expression {@code module.exports}? */
private static boolean isModuleExports(MemberExpression me) {
return !me.isComputed()
&& isIdentifier(me.getObject(), "module")
&& isIdentifier(me.getProperty(), "exports");
}
/** Is {@code e} an identifier with name {@code name}? */
private static boolean isIdentifier(Expression e, String name) {
return e instanceof Identifier && name.equals(((Identifier) e).getName());
}
}
| 6,154 | 34.784884 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/LexicalExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.Comment;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.SourceElement;
import com.semmle.js.ast.Token;
import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.List;
/**
* Extractor for populating lexical information about a JavaScript file, including comments and
* tokens.
*/
public class LexicalExtractor {
private final TextualExtractor textualExtractor;
private final TrapWriter trapwriter;
private final LocationManager locationManager;
private final List<Token> tokens;
private final List<Comment> comments;
public LexicalExtractor(
TextualExtractor textualExtractor, List<Token> tokens, List<Comment> comments) {
this.textualExtractor = textualExtractor;
this.trapwriter = textualExtractor.getTrapwriter();
this.locationManager = textualExtractor.getLocationManager();
this.tokens = tokens;
this.comments = comments;
}
public TrapWriter getTrapwriter() {
return trapwriter;
}
public LocationManager getLocationManager() {
return locationManager;
}
public List<Comment> getComments() {
return comments;
}
public ExtractionMetrics getMetrics() {
return textualExtractor.getMetrics();
}
public LoCInfo extractLines(String src, Label toplevelKey) {
textualExtractor.getMetrics().startPhase(ExtractionPhase.LexicalExtractor_extractLines);
Position end = textualExtractor.extractLines(src, toplevelKey);
LoCInfo info = emitNumlines(toplevelKey, new Position(1, 0, 0), end);
textualExtractor.getMetrics().stopPhase(ExtractionPhase.LexicalExtractor_extractLines);
return info;
}
/**
* Emit line number information for an entity.
*
* @param key the entity key
* @param start the start position of the node
* @param end the end position of the node
*/
public LoCInfo emitNumlines(Label key, Position start, Position end) {
int num_code = 0, num_comment = 0, num_lines = end.getLine() - start.getLine() + 1;
if (tokens != null && comments != null) {
// every line on which there is a (non-EOF) token counts as a line of code
int maxline = 0; // maximum line number on which we've seen a token so far
for (int i = findNode(tokens, start), m = tokens.size(); i < m; ++i) {
Token token = tokens.get(i);
if (token.getLoc().getStart().compareTo(end) >= 0 || token.getType() == Token.Type.EOF)
break;
for (int j = token.getLoc().getStart().getLine(), n = token.getLoc().getEnd().getLine();
j <= n;
++j) {
if (j > maxline) {
// token covers a new line, so increment count and update maxline
maxline = j;
++num_code;
}
}
}
// every line on which there is a comment counts as a line of comment
maxline = 0; // maximum line number on which we've seen a comment so far
for (int i = findNode(comments, start), m = comments.size(); i < m; ++i) {
Comment comment = comments.get(i);
if (comment.getLoc().getStart().compareTo(end) >= 0) break;
for (int j = comment.getLoc().getStart().getLine(), n = comment.getLoc().getEnd().getLine();
j <= n;
++j) {
if (j > maxline) {
// comment covers a new line, so increment count and update maxline
maxline = j;
++num_comment;
}
}
}
}
trapwriter.addTuple("numlines", key, num_lines, num_code, num_comment);
return new LoCInfo(num_code, num_comment);
}
private <T extends SourceElement> int findNode(List<T> ts, Position start) {
int lo = 0, hi = ts.size(), mid;
/**
* Invariant: forall i in [0..lo), ts[i] starts before `start` and forall i in [hi..ts.size()),
* ts[i] starts at or after `start`
*/
while (lo < hi) {
// other parts of the extractor will break long before this could overflow
mid = (lo + hi) >>> 1;
if (ts.get(mid).getLoc().getStart().compareTo(start) >= 0) hi = mid;
else lo = mid + 1;
}
return hi;
}
public void extractTokens(Label toplevelKey) {
textualExtractor.getMetrics().startPhase(ExtractionPhase.LexicalExtractor_extractTokens);
int j = 0;
for (int i = 0, n = tokens.size(), idx = 0; i < n; ++i) {
Token token = tokens.get(i);
if (token == null) continue;
Label key = trapwriter.freshLabel();
int kind = -1;
switch (token.getType()) {
case EOF:
kind = 0;
break;
case NULL:
kind = 1;
break;
case FALSE:
case TRUE:
kind = 2;
break;
case NUM:
kind = 3;
break;
case STRING:
kind = 4;
break;
case REGEXP:
kind = 5;
break;
case NAME:
kind = 6;
break;
case KEYWORD:
kind = 7;
break;
case PUNCTUATOR:
kind = 8;
break;
}
trapwriter.addTuple("tokeninfo", key, kind, toplevelKey, idx++, token.getValue());
locationManager.emitNodeLocation(token, key);
// fill in next_token relation
while (j < comments.size()
&& comments.get(j).getLoc().getEnd().compareTo(token.getLoc().getStart()) <= 0)
trapwriter.addTuple("next_token", this.trapwriter.localID(comments.get(j++)), key);
// the parser sometimes duplicates tokens; skip the second one by nulling it out
if (i + 1 < n) {
Token next = tokens.get(i + 1);
// every token has a unique location
if (token.getLoc().equals(next.getLoc())) tokens.set(i + 1, null);
}
}
textualExtractor.getMetrics().stopPhase(ExtractionPhase.LexicalExtractor_extractTokens);
}
public void extractComments(Label toplevelKey) {
for (Comment comment : comments) {
Label key = this.trapwriter.localID(comment);
String text = comment.getText();
int kind = -1;
switch (comment.getKind()) {
case LINE:
kind = 0;
break;
case HTML_START:
kind = 3;
break;
case HTML_END:
kind = 4;
break;
case BLOCK:
if (comment.isDocComment()) {
kind = 2;
text = text.substring(1);
} else {
kind = 1;
}
break;
}
String tostring = mkToString(comment);
this.trapwriter.addTuple("comments", key, kind, toplevelKey, text, tostring);
this.locationManager.emitNodeLocation(comment, key);
}
}
public String mkToString(SourceElement nd) {
return textualExtractor.mkToString(nd);
}
/** Purge token and comments information to reduce heap pressure. */
public void purge() {
this.tokens.clear();
this.comments.clear();
}
}
| 6,994 | 31.087156 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ExtractorState.java | package com.semmle.js.extractor;
import java.nio.file.Path;
import java.util.concurrent.ConcurrentHashMap;
import com.semmle.js.parser.TypeScriptParser;
/**
* Contains the state to be shared between extractions of different files.
*
* <p>In general, this contains both semantic state that affects the extractor output as well as
* shared resources that are simply expensive to reacquire.
*
* <p>The {@link #reset()} method resets the semantic state while retaining shared resources when
* possible.
*
* <p>Concretely, the shared resource is the Node.js process running the TypeScript compiler, which
* is expensive to restart. The semantic state is the set of projects currently open in that
* process, which affects the type information obtained during extraction of a file.
*/
public class ExtractorState {
private TypeScriptParser typeScriptParser = new TypeScriptParser();
private final ConcurrentHashMap<Path, FileSnippet> snippets = new ConcurrentHashMap<>();
public TypeScriptParser getTypeScriptParser() {
return typeScriptParser;
}
/**
* Returns the mapping that denotes where a snippet file originated from.
*
* <p>The map is thread-safe and may be mutated by the caller.
*/
public ConcurrentHashMap<Path, FileSnippet> getSnippets() {
return snippets;
}
/**
* Makes this semantically equivalent to a fresh state, but may internally retain shared resources
* that are expensive to reacquire.
*/
public void reset() {
typeScriptParser.reset();
snippets.clear();
}
}
| 1,552 | 31.354167 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ExprKinds.java | package com.semmle.js.extractor;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;
import com.semmle.jcorn.TokenType;
import com.semmle.jcorn.jsx.JSXParser;
import com.semmle.js.ast.AssignmentExpression;
import com.semmle.js.ast.BinaryExpression;
import com.semmle.js.ast.ComprehensionBlock;
import com.semmle.js.ast.ComprehensionExpression;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.DynamicImport;
import com.semmle.js.ast.Expression;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.LogicalExpression;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.ast.MetaProperty;
import com.semmle.js.ast.UnaryExpression;
import com.semmle.js.ast.UpdateExpression;
import com.semmle.js.ast.XMLAnyName;
import com.semmle.js.ast.XMLAttributeSelector;
import com.semmle.js.ast.XMLDotDotExpression;
import com.semmle.js.ast.XMLFilterExpression;
import com.semmle.js.ast.XMLQualifiedIdentifier;
import com.semmle.js.ast.jsx.JSXIdentifier;
import com.semmle.js.ast.jsx.JSXMemberExpression;
import com.semmle.js.ast.jsx.JSXSpreadAttribute;
import com.semmle.js.extractor.ASTExtractor.IdContext;
import com.semmle.ts.ast.DecoratorList;
import com.semmle.ts.ast.ExpressionWithTypeArguments;
import com.semmle.ts.ast.TypeAssertion;
import com.semmle.util.exception.CatastrophicError;
/** Map from SpiderMonkey expression types to the numeric kinds used in the DB scheme. */
public class ExprKinds {
private static final Map<String, Integer> binOpKinds = new LinkedHashMap<String, Integer>();
static {
binOpKinds.put("==", 23);
binOpKinds.put("!=", 24);
binOpKinds.put("===", 25);
binOpKinds.put("!==", 26);
binOpKinds.put("<", 27);
binOpKinds.put("<=", 28);
binOpKinds.put(">", 29);
binOpKinds.put(">=", 30);
binOpKinds.put("<<", 31);
binOpKinds.put(">>", 32);
binOpKinds.put(">>>", 33);
binOpKinds.put("+", 34);
binOpKinds.put("-", 35);
binOpKinds.put("*", 36);
binOpKinds.put("/", 37);
binOpKinds.put("%", 38);
binOpKinds.put("|", 39);
binOpKinds.put("^", 40);
binOpKinds.put("&", 41);
binOpKinds.put("in", 42);
binOpKinds.put("instanceof", 43);
binOpKinds.put("&&", 44);
binOpKinds.put("||", 45);
binOpKinds.put("=", 47);
binOpKinds.put("+=", 48);
binOpKinds.put("-=", 49);
binOpKinds.put("*=", 50);
binOpKinds.put("/=", 51);
binOpKinds.put("%=", 52);
binOpKinds.put("<<=", 53);
binOpKinds.put(">>=", 54);
binOpKinds.put(">>>=", 55);
binOpKinds.put("|=", 56);
binOpKinds.put("^=", 57);
binOpKinds.put("&=", 58);
binOpKinds.put("**", 87);
binOpKinds.put("**=", 88);
binOpKinds.put("??", 107);
}
private static final Map<String, Integer> unOpKinds = new LinkedHashMap<String, Integer>();
static {
unOpKinds.put("-", 16);
unOpKinds.put("+", 17);
unOpKinds.put("!", 18);
unOpKinds.put("~", 19);
unOpKinds.put("typeof", 20);
unOpKinds.put("void", 21);
unOpKinds.put("delete", 22);
}
private static final Map<String, Integer> prefixOpKinds = new LinkedHashMap<String, Integer>();
static {
prefixOpKinds.put("++", 59);
prefixOpKinds.put("--", 61);
}
private static final Map<String, Integer> postfixOpKinds = new LinkedHashMap<String, Integer>();
static {
postfixOpKinds.put("++", 60);
postfixOpKinds.put("--", 62);
}
private static final Map<String, Integer> exprKinds = new LinkedHashMap<String, Integer>();
static {
exprKinds.put("ArrayExpression", 7);
exprKinds.put("CallExpression", 13);
exprKinds.put("ConditionalExpression", 11);
exprKinds.put("FunctionExpression", 9);
exprKinds.put("NewExpression", 12);
exprKinds.put("ObjectExpression", 8);
exprKinds.put("SequenceExpression", 10);
exprKinds.put("ThisExpression", 6);
exprKinds.put("ParenthesizedExpression", 63);
exprKinds.put("VariableDeclarator", 64);
exprKinds.put("ArrowFunctionExpression", 65);
exprKinds.put("SpreadElement", 66);
exprKinds.put("ArrayPattern", 67);
exprKinds.put("ObjectPattern", 68);
exprKinds.put("YieldExpression", 69);
exprKinds.put("TaggedTemplateExpression", 70);
exprKinds.put("TemplateLiteral", 71);
exprKinds.put("TemplateElement", 72);
exprKinds.put("LetExpression", 77);
exprKinds.put("ClassExpression", 80);
exprKinds.put("Super", 81);
exprKinds.put("ImportSpecifier", 83);
exprKinds.put("ImportDefaultSpecifier", 84);
exprKinds.put("ImportNamespaceSpecifier", 85);
exprKinds.put("ExportSpecifier", 86);
exprKinds.put("JSXElement", 89);
exprKinds.put("JSXNamespacedName", 90);
exprKinds.put("JSXEmptyExpression", 91);
exprKinds.put("AwaitExpression", 92);
exprKinds.put("Decorator", 94);
exprKinds.put("ExportDefaultSpecifier", 95);
exprKinds.put("ExportNamespaceSpecifier", 96);
exprKinds.put("BindExpression", 97);
exprKinds.put("ExternalModuleReference", 98);
exprKinds.put("NonNullAssertion", 105);
}
private static final Map<IdContext, Integer> idKinds =
new EnumMap<IdContext, Integer>(IdContext.class);
static {
idKinds.put(IdContext.label, 0);
idKinds.put(IdContext.varDecl, 78);
idKinds.put(IdContext.varAndTypeDecl, 78);
idKinds.put(IdContext.namespaceDecl, 78);
idKinds.put(IdContext.varAndNamespaceDecl, 78);
idKinds.put(IdContext.varAndTypeAndNamespaceDecl, 78);
idKinds.put(IdContext.typeOnlyImport, 78);
idKinds.put(IdContext.typeOnlyExport, 103);
idKinds.put(IdContext.varBind, 79);
idKinds.put(IdContext.export, 103);
idKinds.put(IdContext.exportBase, 103);
}
public static int getExprKind(final Expression expr, final IdContext idContext) {
Integer kind =
expr.accept(
new DefaultVisitor<Void, Integer>() {
@Override
public Integer visit(Expression nd, Void q) {
return exprKinds.get(nd.getType());
}
@Override
public Integer visit(AssignmentExpression nd, Void q) {
return binOpKinds.get(nd.getOperator());
}
@Override
public Integer visit(BinaryExpression nd, Void q) {
return binOpKinds.get(nd.getOperator());
}
@Override
public Integer visit(Identifier nd, Void c) {
return idKinds.get(idContext);
}
@Override
public Integer visit(JSXIdentifier nd, Void c) {
return visit((Identifier) nd, c);
}
@Override
public Integer visit(LogicalExpression nd, Void q) {
return binOpKinds.get(nd.getOperator());
}
@Override
public Integer visit(Literal nd, Void q) {
TokenType tp = nd.getTokenType();
if (tp == TokenType._null) return 1;
if (tp == TokenType._true || tp == TokenType._false) return 2;
if (tp == TokenType.num) return 3;
if (tp == TokenType.string || tp == JSXParser.jsxText) return 4;
if (tp == TokenType.regexp) return 5;
if (tp == TokenType.bigint) return 106;
throw new CatastrophicError("Unexpected literal with token type " + tp.label);
}
@Override
public Integer visit(MemberExpression nd, Void q) {
return nd.isComputed() ? 15 : 14;
}
@Override
public Integer visit(JSXMemberExpression nd, Void c) {
// treat JSX member expressions as dot expressions
return 14;
}
@Override
public Integer visit(JSXSpreadAttribute nd, Void c) {
// treat JSX spread attributes as spread elements
return exprKinds.get("SpreadElement");
}
@Override
public Integer visit(UnaryExpression nd, Void q) {
return unOpKinds.get(nd.getOperator());
}
@Override
public Integer visit(UpdateExpression nd, Void q) {
return nd.isPrefix()
? prefixOpKinds.get(nd.getOperator())
: postfixOpKinds.get(nd.getOperator());
}
@Override
public Integer visit(ComprehensionExpression nd, Void q) {
return nd.isGenerator() ? 74 : 73;
}
@Override
public Integer visit(ComprehensionBlock nd, Void q) {
return nd.isOf() ? 76 : 75;
}
@Override
public Integer visit(MetaProperty nd, Void c) {
if (nd.getMeta().getName().equals("new")) return 82; // @newtargetexpr
if (nd.getMeta().getName().equals("import")) return 115; // @importmetaexpr
return 93; // @functionsentexpr
}
@Override
public Integer visit(DynamicImport nd, Void c) {
return 99;
}
@Override
public Integer visit(ExpressionWithTypeArguments nd, Void c) {
return 100;
}
@Override
public Integer visit(TypeAssertion nd, Void c) {
return nd.isAsExpression() ? 102 : 101;
}
@Override
public Integer visit(DecoratorList nd, Void c) {
return 104;
}
@Override
public Integer visit(XMLAnyName nd, Void c) {
return 108;
}
@Override
public Integer visit(XMLAttributeSelector nd, Void c) {
return nd.isComputed() ? 110 : 109;
}
@Override
public Integer visit(XMLFilterExpression nd, Void c) {
return 111;
}
@Override
public Integer visit(XMLQualifiedIdentifier nd, Void c) {
return nd.isComputed() ? 113 : 112;
}
@Override
public Integer visit(XMLDotDotExpression nd, Void c) {
return 114;
}
},
null);
if (kind == null)
throw new CatastrophicError("Unsupported expression kind: " + expr.getClass());
return kind;
}
}
| 10,576 | 33.119355 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ASTExtractor.java | package com.semmle.js.extractor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import com.semmle.js.ast.AClass;
import com.semmle.js.ast.AFunction;
import com.semmle.js.ast.AFunctionExpression;
import com.semmle.js.ast.ArrayExpression;
import com.semmle.js.ast.ArrayPattern;
import com.semmle.js.ast.ArrowFunctionExpression;
import com.semmle.js.ast.AssignmentExpression;
import com.semmle.js.ast.AssignmentPattern;
import com.semmle.js.ast.AwaitExpression;
import com.semmle.js.ast.BinaryExpression;
import com.semmle.js.ast.BindExpression;
import com.semmle.js.ast.BlockStatement;
import com.semmle.js.ast.CallExpression;
import com.semmle.js.ast.CatchClause;
import com.semmle.js.ast.ClassBody;
import com.semmle.js.ast.ClassDeclaration;
import com.semmle.js.ast.ClassExpression;
import com.semmle.js.ast.ComprehensionBlock;
import com.semmle.js.ast.ComprehensionExpression;
import com.semmle.js.ast.ConditionalExpression;
import com.semmle.js.ast.DeclarationFlags;
import com.semmle.js.ast.Decorator;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.DoWhileStatement;
import com.semmle.js.ast.DynamicImport;
import com.semmle.js.ast.EnhancedForStatement;
import com.semmle.js.ast.ExportAllDeclaration;
import com.semmle.js.ast.ExportDefaultDeclaration;
import com.semmle.js.ast.ExportNamedDeclaration;
import com.semmle.js.ast.ExportSpecifier;
import com.semmle.js.ast.Expression;
import com.semmle.js.ast.ExpressionStatement;
import com.semmle.js.ast.FieldDefinition;
import com.semmle.js.ast.ForOfStatement;
import com.semmle.js.ast.ForStatement;
import com.semmle.js.ast.FunctionDeclaration;
import com.semmle.js.ast.FunctionExpression;
import com.semmle.js.ast.IFunction;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.IPattern;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.IfStatement;
import com.semmle.js.ast.ImportDeclaration;
import com.semmle.js.ast.ImportSpecifier;
import com.semmle.js.ast.InvokeExpression;
import com.semmle.js.ast.JumpStatement;
import com.semmle.js.ast.LabeledStatement;
import com.semmle.js.ast.LetExpression;
import com.semmle.js.ast.LetStatement;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.LogicalExpression;
import com.semmle.js.ast.MemberDefinition;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.ast.MetaProperty;
import com.semmle.js.ast.MethodDefinition;
import com.semmle.js.ast.MethodDefinition.Kind;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.ObjectExpression;
import com.semmle.js.ast.ObjectPattern;
import com.semmle.js.ast.ParenthesizedExpression;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.Program;
import com.semmle.js.ast.Property;
import com.semmle.js.ast.RestElement;
import com.semmle.js.ast.ReturnStatement;
import com.semmle.js.ast.SequenceExpression;
import com.semmle.js.ast.SourceElement;
import com.semmle.js.ast.SourceLocation;
import com.semmle.js.ast.SpreadElement;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.Super;
import com.semmle.js.ast.SwitchCase;
import com.semmle.js.ast.SwitchStatement;
import com.semmle.js.ast.TaggedTemplateExpression;
import com.semmle.js.ast.TemplateElement;
import com.semmle.js.ast.TemplateLiteral;
import com.semmle.js.ast.ThrowStatement;
import com.semmle.js.ast.TryStatement;
import com.semmle.js.ast.UnaryExpression;
import com.semmle.js.ast.UpdateExpression;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.js.ast.VariableDeclarator;
import com.semmle.js.ast.WhileStatement;
import com.semmle.js.ast.WithStatement;
import com.semmle.js.ast.XMLAttributeSelector;
import com.semmle.js.ast.XMLDotDotExpression;
import com.semmle.js.ast.XMLFilterExpression;
import com.semmle.js.ast.XMLQualifiedIdentifier;
import com.semmle.js.ast.YieldExpression;
import com.semmle.js.ast.jsx.IJSXName;
import com.semmle.js.ast.jsx.JSXAttribute;
import com.semmle.js.ast.jsx.JSXElement;
import com.semmle.js.ast.jsx.JSXEmptyExpression;
import com.semmle.js.ast.jsx.JSXExpressionContainer;
import com.semmle.js.ast.jsx.JSXIdentifier;
import com.semmle.js.ast.jsx.JSXMemberExpression;
import com.semmle.js.ast.jsx.JSXNamespacedName;
import com.semmle.js.ast.jsx.JSXOpeningElement;
import com.semmle.js.ast.jsx.JSXSpreadAttribute;
import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.extractor.ScopeManager.DeclKind;
import com.semmle.js.extractor.ScopeManager.Scope;
import com.semmle.js.parser.ParseError;
import com.semmle.ts.ast.ArrayTypeExpr;
import com.semmle.ts.ast.ConditionalTypeExpr;
import com.semmle.ts.ast.DecoratorList;
import com.semmle.ts.ast.EnumDeclaration;
import com.semmle.ts.ast.EnumMember;
import com.semmle.ts.ast.ExportAsNamespaceDeclaration;
import com.semmle.ts.ast.ExportWholeDeclaration;
import com.semmle.ts.ast.ExpressionWithTypeArguments;
import com.semmle.ts.ast.ExternalModuleDeclaration;
import com.semmle.ts.ast.ExternalModuleReference;
import com.semmle.ts.ast.FunctionTypeExpr;
import com.semmle.ts.ast.GenericTypeExpr;
import com.semmle.ts.ast.GlobalAugmentationDeclaration;
import com.semmle.ts.ast.INodeWithSymbol;
import com.semmle.ts.ast.ITypedAstNode;
import com.semmle.ts.ast.ImportTypeExpr;
import com.semmle.ts.ast.ImportWholeDeclaration;
import com.semmle.ts.ast.IndexedAccessTypeExpr;
import com.semmle.ts.ast.InferTypeExpr;
import com.semmle.ts.ast.InterfaceDeclaration;
import com.semmle.ts.ast.InterfaceTypeExpr;
import com.semmle.ts.ast.IntersectionTypeExpr;
import com.semmle.ts.ast.KeywordTypeExpr;
import com.semmle.ts.ast.MappedTypeExpr;
import com.semmle.ts.ast.NamespaceDeclaration;
import com.semmle.ts.ast.NonNullAssertion;
import com.semmle.ts.ast.OptionalTypeExpr;
import com.semmle.ts.ast.ParenthesizedTypeExpr;
import com.semmle.ts.ast.PredicateTypeExpr;
import com.semmle.ts.ast.RestTypeExpr;
import com.semmle.ts.ast.TupleTypeExpr;
import com.semmle.ts.ast.TypeAliasDeclaration;
import com.semmle.ts.ast.TypeAssertion;
import com.semmle.ts.ast.TypeExpression;
import com.semmle.ts.ast.TypeParameter;
import com.semmle.ts.ast.TypeofTypeExpr;
import com.semmle.ts.ast.UnaryTypeExpr;
import com.semmle.ts.ast.UnionTypeExpr;
import com.semmle.util.collections.CollectionUtil;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
/** Extractor for AST-based information; invoked by the {@link JSExtractor}. */
public class ASTExtractor {
private final TrapWriter trapwriter;
private final LocationManager locationManager;
private final SyntacticContextManager contextManager;
private final ScopeManager scopeManager;
private final Label toplevelLabel;
private final LexicalExtractor lexicalExtractor;
private final RegExpExtractor regexpExtractor;
public ASTExtractor(LexicalExtractor lexicalExtractor, ScopeManager scopeManager) {
this.trapwriter = lexicalExtractor.getTrapwriter();
this.locationManager = lexicalExtractor.getLocationManager();
this.contextManager = new SyntacticContextManager();
this.scopeManager = scopeManager;
this.lexicalExtractor = lexicalExtractor;
this.regexpExtractor = new RegExpExtractor(trapwriter, locationManager);
this.toplevelLabel =
trapwriter.globalID(
"script;{"
+ locationManager.getFileLabel()
+ "},"
+ locationManager.getStartLine()
+ ','
+ locationManager.getStartColumn());
}
public TrapWriter getTrapwriter() {
return trapwriter;
}
public LocationManager getLocationManager() {
return locationManager;
}
public Label getToplevelLabel() {
return toplevelLabel;
}
public ScopeManager getScopeManager() {
return scopeManager;
}
public ExtractionMetrics getMetrics() {
return lexicalExtractor.getMetrics();
}
/**
* The binding semantics for an identifier.
*
* <p>An identifier is either a label, or declares or binds to a variable or type.
*/
public enum IdContext {
/** An identifier that binds to a variable. */
varBind,
/** An identifier that declares a variable. */
varDecl,
/** An identifier that declares both a variable and a type. */
varAndTypeDecl,
/**
* An identifier that is not associated with variables or types, such as a property name and
* statement label.
*/
label,
/** An identifier that binds to a type (and not a variable). */
typeBind,
/** An identifier that declares a type (and not a variable). */
typeDecl,
/**
* An identifier that is part of a type, but should not bind to a type name. Unlike {@link
* #label}, this will not result in an expression.
*/
typeLabel,
/**
* An identifier that refers to a variable from inside a type, i.e. the operand to a
* <tt>typeof</tt> type or left operand to an <tt>is</tt> type.
*
* <p>This is generally treated as a type, except a variable binding will be emitted for it.
*/
varInTypeBind,
/** An identifier that refers to a namespace from inside a type. */
namespaceBind,
/** An identifier that declares a namespace. */
namespaceDecl,
/** An identifier that declares a variable and a namespace. */
varAndNamespaceDecl,
/**
* An identifier that occurs in a type-only import.
*
* These may declare a type and/or a namespace, but for compatibility with our AST,
* must be emitted as a VarDecl (with no variable binding).
*/
typeOnlyImport,
/**
* An identifier that occurs in a type-only export.
*
* These may refer to a type and/or a namespace, but for compatibility with our AST,
* must be emitted as an ExportVarAccess (with no variable binding).
*/
typeOnlyExport,
/** An identifier that declares a variable, type, and namepsace. */
varAndTypeAndNamespaceDecl,
/**
* An identifier that occurs as part of a named export, such as <tt>export { A }</tt>.
*
* <p>This may refer to a variable, type, and/or a namespace, and will export exactly those that
* can be resolved.
*
* <p>In this case, the identifier is not implicitly resolved to a global unless the global is
* explicitly declared, since TypeScript only emits the export code when it refers to a declared
* variable.
*/
export,
/**
* An identifier that occurs as a qualified name in a default export expression, such as
* <tt>A</tt> in <tt>export default A.B</tt>.
*
* <p>This acts like {@link #export}, except it cannot refer to a type (i.e. it must be a
* variable and/or a namespace).
*/
exportBase;
/**
* True if this occurs as part of a type annotation, i.e. it is {@link #typeBind} or {@link
* #typeDecl}, {@link #typeLabel}, {@link #varInTypeBind}, or {@link #namespaceBind}.
*
* <p>Does not hold for {@link #varAndTypeDecl}, {@link #typeOnlyImport}, or @{link {@link #typeOnlyExport}
* as these do not occur in type annotations.
*/
public boolean isInsideType() {
return this == typeBind
|| this == typeDecl
|| this == typeLabel
|| this == varInTypeBind
|| this == namespaceBind;
}
};
private static class Context {
private final Label parent;
private final int childIndex;
private final IdContext idcontext;
public Context(Label parent, int childIndex, IdContext idcontext) {
this.parent = parent;
this.childIndex = childIndex;
this.idcontext = idcontext;
}
/** True if the visited AST node occurs as part of a type annotation. */
public boolean isInsideType() {
return idcontext.isInsideType();
}
}
private class V extends DefaultVisitor<Context, Label> {
private final Platform platform;
private final SourceType sourceType;
private boolean isStrict;
private List<ParseError> additionalErrors = new ArrayList<>();
public V(Platform platform, SourceType sourceType) {
this.platform = platform;
this.sourceType = sourceType;
this.isStrict = sourceType.isStrictMode();
}
private Label visit(INode child, Label parent, int childIndex) {
return visit(child, parent, childIndex, IdContext.varBind);
}
private Label visitAll(List<? extends INode> children, Label parent) {
return visitAll(children, parent, IdContext.varBind, 0);
}
private Label visit(INode child, Label parent, int childIndex, IdContext idContext) {
if (child == null) return null;
return child.accept(this, new Context(parent, childIndex, idContext));
}
private Label visitAll(
List<? extends INode> children, Label parent, IdContext idContext, int index) {
return visitAll(children, parent, idContext, index, 1);
}
private Label visitAll(
List<? extends INode> children, Label parent, IdContext idContext, int index, int step) {
Label res = null;
for (INode child : children) {
res = visit(child, parent, index, idContext);
index += step;
}
return res;
}
@Override
public Label visit(Expression nd, Context c) {
int kind =
c.isInsideType()
? TypeExprKinds.getTypeExprKind(nd, c.idcontext)
: ExprKinds.getExprKind(nd, c.idcontext);
Label lbl = visit(nd, kind, c);
emitStaticType(nd, lbl);
return lbl;
}
@Override
public Label visit(TypeExpression nd, Context c) {
Label lbl = visit(nd, TypeExprKinds.getTypeExprKind(nd, c.idcontext), c);
emitStaticType(nd, lbl);
return lbl;
}
private void emitStaticType(ITypedAstNode nd, Label lbl) {
if (nd.getStaticTypeId() != -1) {
trapwriter.addTuple(
"ast_node_type", lbl, trapwriter.globalID("type;" + nd.getStaticTypeId()));
}
}
private Label visit(SourceElement nd, int kind, Context c) {
return visit(nd, kind, lexicalExtractor.mkToString(nd), c);
}
protected Label visit(SourceElement nd, int kind, String tostring, Context c) {
Label lbl = trapwriter.localID(nd);
if (c.isInsideType()) {
trapwriter.addTuple("typeexprs", lbl, kind, c.parent, c.childIndex, tostring);
} else {
trapwriter.addTuple("exprs", lbl, kind, c.parent, c.childIndex, tostring);
}
if (nd.hasLoc()) locationManager.emitNodeLocation(nd, lbl);
Statement enclosingStmt = contextManager.getCurrentStatement();
if (enclosingStmt != null)
trapwriter.addTuple("enclosingStmt", lbl, trapwriter.localID(enclosingStmt));
trapwriter.addTuple("exprContainers", lbl, contextManager.getCurrentContainerKey());
return lbl;
}
@Override
public Label visit(Statement nd, Context c) {
Label lbl = trapwriter.localID(nd);
int kind = StmtKinds.getStmtKind(nd);
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("stmts", lbl, kind, c.parent, c.childIndex, tostring);
locationManager.emitNodeLocation(nd, lbl);
trapwriter.addTuple("stmtContainers", lbl, contextManager.getCurrentContainerKey());
contextManager.setCurrentStatement(nd);
return lbl;
}
@Override
public Label visit(InvokeExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getCallee(), key, -1);
visitAll(nd.getTypeArguments(), key, IdContext.typeBind, -2, -1);
visitAll(nd.getArguments(), key);
if (nd.getResolvedSignatureId() != -1) {
Label signature = trapwriter.globalID("signature;" + nd.getResolvedSignatureId());
trapwriter.addTuple("invoke_expr_signature", key, signature);
}
if (nd.getOverloadIndex() != -1) {
trapwriter.addTuple("invoke_expr_overload_index", key, nd.getOverloadIndex());
}
if (nd.isOptional()) {
trapwriter.addTuple("isOptionalChaining", key);
}
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(ExpressionStatement nd, Context c) {
Label key = super.visit(nd, c);
return visit(nd.getExpression(), key, 0);
}
private void addVariableBinding(String relation, Label key, String name) {
Label variableKey = scopeManager.getVarKey(name);
trapwriter.addTuple(relation, key, variableKey);
}
private boolean addTypeBinding(String relation, Label key, String name) {
// Type bindings do not implicitly resolve to a global - they are null if unresolved.
Label typenameKey = scopeManager.getTypeKey(name);
if (typenameKey != null) {
trapwriter.addTuple(relation, key, typenameKey);
return true;
}
return false;
}
private boolean addNamespaceBinding(String relation, Label key, String name) {
// Namespace bindings do not implicitly resolve to a global - they are null if
// unresolved.
Label typenameKey = scopeManager.getNamespaceKey(name);
if (typenameKey != null) {
trapwriter.addTuple(relation, key, typenameKey);
return true;
}
return false;
}
@Override
public Label visit(Identifier nd, Context c) {
Label key = super.visit(nd, c);
String name = nd.getName();
emitNodeSymbol(nd, key);
trapwriter.addTuple("literals", name, name, key);
switch (c.idcontext) {
case varBind:
case varInTypeBind:
addVariableBinding("bind", key, name);
break;
case varDecl:
addVariableBinding("decl", key, name);
break;
case varAndTypeDecl:
addVariableBinding("decl", key, name);
addTypeBinding("typedecl", key, name);
break;
case typeBind:
addTypeBinding("typebind", key, name);
break;
case typeDecl:
addTypeBinding("typedecl", key, name);
break;
case namespaceBind:
addNamespaceBinding("namespacebind", key, name);
break;
case namespaceDecl:
addNamespaceBinding("namespacedecl", key, name);
break;
case varAndNamespaceDecl:
addVariableBinding("decl", key, name);
addNamespaceBinding("namespacedecl", key, name);
break;
case typeOnlyImport:
addTypeBinding("typedecl", key, name);
addNamespaceBinding("namespacedecl", key, name);
break;
case typeOnlyExport:
addTypeBinding("typebind", key, name);
addNamespaceBinding("namespacebind", key, name);
break;
case varAndTypeAndNamespaceDecl:
addVariableBinding("decl", key, name);
addTypeBinding("typedecl", key, name);
addNamespaceBinding("namespacedecl", key, name);
break;
case export:
case exportBase:
// At the time of writing, this kind of export is only allowed at the top-level.
boolean resolved = false;
if (c.idcontext != IdContext.exportBase) {
resolved |= addTypeBinding("typebind", key, name);
}
resolved |= addNamespaceBinding("namespacebind", key, name);
if (scopeManager.isStrictlyInScope(name) || !resolved) {
// Do not reference implicit globals, unless nothing else is in scope.
addVariableBinding("bind", key, name);
}
break;
case label:
case typeLabel:
break;
}
return key;
}
@Override
public Label visit(Literal nd, Context c) {
Label key = super.visit(nd, c);
String source = nd.getLoc().getSource();
String valueString = nd.getStringValue();
trapwriter.addTuple("literals", valueString, source, key);
if (nd.isRegExp()) {
OffsetTranslation offsets = new OffsetTranslation();
offsets.set(0, 1); // skip the initial '/'
regexpExtractor.extract(source.substring(1, source.lastIndexOf('/')), offsets, nd, false);
} else if (nd.isStringLiteral() && !c.isInsideType() && nd.getRaw().length() < 1000) {
regexpExtractor.extract(valueString, makeStringLiteralOffsets(nd.getRaw()), nd, true);
}
return key;
}
private boolean isOctalDigit(char ch) {
return '0' <= ch && ch <= '7';
}
/**
* Builds a translation from offsets in a string value back to its original raw literal text
* (including quotes).
*
* <p>This is not a 1:1 mapping since escape sequences take up more characters in the raw
* literal than in the resulting string value. This mapping includes the surrounding quotes.
*
* <p>For example: for the raw literal value <code>'x\.y'</code> (quotes included), the <code>y
* </code> at index 2 in <code>x.y</code> maps to index 4 in the raw literal.
*/
public OffsetTranslation makeStringLiteralOffsets(String rawLiteral) {
OffsetTranslation offsets = new OffsetTranslation();
offsets.set(0, 1); // Skip the initial quote
// Invariant: raw character at 'pos' corresponds to decoded character at 'pos - delta'
int pos = 1;
int delta = 1;
while (pos < rawLiteral.length() - 1) {
if (rawLiteral.charAt(pos) != '\\') {
++pos;
continue;
}
final int length; // Length of the escape sequence, including slash.
int outputLength = 1; // Number characters the sequence expands to.
char ch = rawLiteral.charAt(pos + 1);
if ('0' <= ch && ch <= '7') {
// Octal escape: \N, \NN, or \NNN
int firstDigit = pos + 1;
int end = firstDigit;
int maxEnd = Math.min(firstDigit + (ch <= '3' ? 3 : 2), rawLiteral.length());
while (end < maxEnd && isOctalDigit(rawLiteral.charAt(end))) {
++end;
}
length = end - pos;
} else if (ch == 'x') {
// Hex escape: \xNN
length = 4;
} else if (ch == 'u' && pos + 2 < rawLiteral.length()) {
if (rawLiteral.charAt(pos + 2) == '{') {
// Variable-length unicode escape: \U{N...}
// Scan for the ending '}'
int firstDigit = pos + 3;
int end = firstDigit;
int leadingZeros = 0;
while (end < rawLiteral.length() && rawLiteral.charAt(end) == '0') {
++end;
++leadingZeros;
}
while (end < rawLiteral.length() && rawLiteral.charAt(end) != '}') {
++end;
}
int numDigits = end - firstDigit;
if (numDigits - leadingZeros > 4) {
outputLength = 2; // Encoded as a surrogate pair
}
++end; // Include '}' character
length = end - pos;
} else {
// Fixed-length unicode escape: \UNNNN
length = 6;
}
} else {
// Simple escape: \n or similar.
length = 2;
}
int end = pos + length;
if (end > rawLiteral.length()) {
end = rawLiteral.length();
}
int outputPos = pos - delta;
// Map the next character to the adjusted offset.
offsets.set(outputPos + outputLength, end);
delta += length - outputLength;
pos = end;
}
return offsets;
}
@Override
public Label visit(MemberExpression nd, Context c) {
Label key = super.visit(nd, c);
if (c.isInsideType()) {
emitNodeSymbol(nd, key);
// The context can either be typeBind, namespaceBind, or varInTypeBind.
IdContext baseIdContext =
c.idcontext == IdContext.varInTypeBind
? IdContext.varInTypeBind
: IdContext.namespaceBind;
visit(nd.getObject(), key, 0, baseIdContext);
// Ensure the property name is not a TypeAccess, since this would create two
// TypeAccesses from the same type usage, easily leading to duplicate query
// results. The qualified access is the one we prefer to select.
visit(nd.getProperty(), key, 1, IdContext.typeLabel);
} else {
IdContext baseIdContext =
c.idcontext == IdContext.export ? IdContext.exportBase : IdContext.varBind;
visit(nd.getObject(), key, 0, baseIdContext);
visit(nd.getProperty(), key, 1, nd.isComputed() ? IdContext.varBind : IdContext.label);
}
if (nd.isOptional()) {
trapwriter.addTuple("isOptionalChaining", key);
}
return key;
}
@Override
public Label visit(Program nd, Context c) {
contextManager.enterContainer(toplevelLabel);
isStrict = hasUseStrict(nd.getBody());
// Add platform-specific globals.
scopeManager.addVariables(platform.getPredefinedGlobals());
// Introduce local scope if there is one.
if (sourceType.hasLocalScope()) {
Label moduleScopeKey =
trapwriter.globalID(
"module;{"
+ locationManager.getFileLabel()
+ "},"
+ locationManager.getStartLine()
+ ","
+ locationManager.getStartColumn());
scopeManager.enterScope(3, moduleScopeKey, toplevelLabel);
scopeManager.addVariables(
sourceType.getPredefinedLocals(platform, locationManager.getSourceFileExtension()));
trapwriter.addTuple("isModule", toplevelLabel);
}
// Emit the specific source type.
switch (sourceType) {
case CLOSURE_MODULE:
trapwriter.addTuple("isClosureModule", toplevelLabel);
break;
case MODULE:
trapwriter.addTuple("isES2015Module", toplevelLabel);
break;
default:
break;
}
// add all declared global (or module-scoped) names, both non-lexical and lexical
scopeManager.addNames(scopeManager.collectDeclaredNames(nd, isStrict, false, DeclKind.none));
scopeManager.addNames(scopeManager.collectDeclaredNames(nd, isStrict, true, DeclKind.none));
visitAll(nd.getBody(), toplevelLabel);
// Leave the local scope again.
if (sourceType.hasLocalScope()) scopeManager.leaveScope();
contextManager.leaveContainer();
emitNodeSymbol(nd, toplevelLabel);
return toplevelLabel;
}
/** Is the first statement of {@code body} a strict mode declaration? */
private boolean hasUseStrict(List<Statement> body) {
if (!body.isEmpty()) {
Statement firstStmt = body.get(0);
if (firstStmt instanceof ExpressionStatement) {
Expression e = ((ExpressionStatement) firstStmt).getExpression();
if (e instanceof Literal) {
String r = ((Literal) e).getRaw();
return "'use strict'".equals(r) || "\"use strict\"".equals(r);
}
}
}
return false;
}
@Override
public Label visit(AssignmentExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1);
return key;
}
@Override
public Label visit(BinaryExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1);
return key;
}
@Override
public Label visit(ComprehensionBlock nd, Context c) {
Label key = super.visit(nd, c);
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(nd.getLeft(), isStrict, true, DeclKind.var);
scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
visit(nd.getLeft(), key, 0, IdContext.varDecl);
visit(nd.getRight(), key, 1);
return key;
}
@Override
public Label visit(ComprehensionExpression nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getBlocks(), key, IdContext.varBind, 1);
visit(nd.getFilter(), key, -1);
visit(nd.getBody(), key, 0);
for (int i = nd.getBlocks().size(); i > 0; --i) scopeManager.leaveScope();
return key;
}
@Override
public Label visit(LogicalExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1);
return key;
}
@Override
public Label visit(UnaryExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0);
return key;
}
@Override
public Label visit(SpreadElement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0);
return key;
}
@Override
public Label visit(UpdateExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0);
return key;
}
@Override
public Label visit(YieldExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0);
if (nd.isDelegating()) trapwriter.addTuple("isDelegating", key);
return key;
}
/*
* Caveat: If you change this method, check whether you also need to change the
* handling of for loops with let-bound loop variables above.
*/
@Override
public Label visit(VariableDeclaration nd, Context c) {
Label key = super.visit(nd, c);
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", key);
}
visitAll(nd.getDeclarations(), key);
return key;
}
@Override
public Label visit(LetStatement nd, Context c) {
return extractLet(nd, super.visit(nd, c), nd.getHead(), nd.getBody());
}
@Override
public Label visit(LetExpression nd, Context c) {
return extractLet(nd, super.visit(nd, c), nd.getHead(), nd.getBody());
}
private Label extractLet(Node nd, Label key, List<VariableDeclarator> head, Node body) {
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(head, isStrict, true, DeclKind.var);
scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
visitAll(head, key);
visit(body, key, -1, IdContext.varBind);
scopeManager.leaveScope();
return key;
}
@Override
public Label visit(VariableDeclarator nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getId(), key, 0, IdContext.varDecl);
visit(nd.getInit(), key, 1);
visit(nd.getTypeAnnotation(), key, 2, IdContext.typeBind);
for (int i = 0; i < DeclarationFlags.numberOfFlags; ++i) {
if (DeclarationFlags.hasNthFlag(nd.getFlags(), i)) {
trapwriter.addTuple(DeclarationFlags.relationNames.get(i), key);
}
}
return key;
}
@Override
public Label visit(BlockStatement nd, Context c) {
Label key = super.visit(nd, c);
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, true, DeclKind.none);
if (!lexicals.isEmpty()) {
scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
}
visitAll(nd.getBody(), key);
if (!lexicals.isEmpty()) scopeManager.leaveScope();
return key;
}
@Override
public Label visit(FunctionDeclaration nd, Context c) {
Label key = super.visit(nd, c);
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", key);
}
extractFunction(nd, key);
emitStaticType(nd, key);
return key;
}
private void extractFunctionAttributes(IFunction nd, Label key) {
if (nd.isGenerator()) trapwriter.addTuple("isGenerator", key);
if (nd.hasRest()) trapwriter.addTuple("hasRestParameter", key);
if (nd.isAsync()) trapwriter.addTuple("isAsync", key);
}
@Override
public Label visit(AFunctionExpression nd, Context c) {
Label key = super.visit(nd, c);
extractFunction(nd, key);
return key;
}
private void extractFunction(IFunction nd, Label key) {
// If the function has no body we process it like any other function, it
// just won't contain any statements.
contextManager.enterContainer(key);
boolean bodyIsStrict = isStrict;
if (!isStrict && nd.getBody() instanceof BlockStatement)
bodyIsStrict = hasUseStrict(((BlockStatement) nd.getBody()).getBody());
// The name of a function declaration binds to the outer scope.
if (nd instanceof FunctionDeclaration) {
visit(nd.getId(), key, -1, IdContext.varDecl);
}
DeclaredNames locals =
scopeManager.collectDeclaredNames(nd.getBody(), bodyIsStrict, false, DeclKind.none);
scopeManager.enterScope((Node) nd);
scopeManager.addNames(locals);
// The name of a function expression binds to its own scope.
if (nd.getId() != null && nd instanceof AFunctionExpression) {
scopeManager.addVariables(nd.getId().getName());
visit(nd.getId(), key, -1, IdContext.varDecl);
}
for (TypeParameter tp : nd.getTypeParameters()) {
scopeManager.addTypeName(tp.getId().getName());
}
int i = 0;
for (IPattern param : nd.getAllParams()) {
scopeManager.addNames(
scopeManager.collectDeclaredNames(param, isStrict, false, DeclKind.var));
Label paramKey = visit(param, key, i, IdContext.varDecl);
// Extract optional parameters
if (nd.getOptionalParameterIndices().contains(i)) {
trapwriter.addTuple("isOptionalParameterDeclaration", paramKey);
}
++i;
}
// add 'arguments' object unless this is an arrow function
if (!(nd instanceof ArrowFunctionExpression)) {
if (!scopeManager.declaredInCurrentScope("arguments"))
scopeManager.addVariables("arguments");
trapwriter.addTuple("isArgumentsObject", scopeManager.getVarKey("arguments"));
}
// add return type at index -3
visit(nd.getReturnType(), key, -3, IdContext.typeBind);
// add 'this' type at index -4
visit(nd.getThisParameterType(), key, -4, IdContext.typeBind);
// add parameter stuff at index -5 and down
extractParameterDefaultsAndTypes(nd, key, i);
extractFunctionAttributes(nd, key);
// Extract associated symbol and signature
emitNodeSymbol(nd, key);
if (nd.getDeclaredSignatureId() != -1) {
Label signatureKey = trapwriter.globalID("signature;" + nd.getDeclaredSignatureId());
trapwriter.addTuple("declared_function_signature", key, signatureKey);
}
boolean oldIsStrict = isStrict;
isStrict = bodyIsStrict;
this.visit(nd.getBody(), key, -2);
isStrict = oldIsStrict;
contextManager.leaveContainer();
scopeManager.leaveScope();
}
private void extractParameterDefaultsAndTypes(IFunction nd, Label key, int paramCount) {
for (int j = 0; j < paramCount; ++j) {
// parameter defaults are populated at indices -5, -9, ...
if (nd.hasDefault(j)) this.visit(nd.getDefault(j), key, -(4 * j + 5));
// parameter type annotations are populated at indices -6, -10, ...
if (nd.hasParameterType(j))
this.visit(nd.getParameterType(j), key, -(4 * j + 6), IdContext.typeBind);
}
// type parameters are at indices -7, -11, -15, ...
visitAll(nd.getTypeParameters(), key, IdContext.typeDecl, -7, -4);
// parameter decorators are at indices -8, -12, -16, ...
visitAll(nd.getParameterDecorators(), key, IdContext.varBind, -8, -4);
}
@Override
public Label visit(SwitchStatement nd, Context c) {
Label key = super.visit(nd, c);
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(nd.getCases(), isStrict, true, DeclKind.none);
visit(nd.getDiscriminant(), key, -1);
if (!lexicals.isEmpty()) {
scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
}
contextManager.enterSwitchStatement(nd);
visitAll(nd.getCases(), key);
contextManager.leaveSwitchStatement();
if (!lexicals.isEmpty()) scopeManager.leaveScope();
return key;
}
@Override
public Label visit(SwitchCase nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTest(), key, -1);
visitAll(nd.getConsequent(), key);
return key;
}
@Override
public Label visit(ForStatement nd, Context c) {
Label key = super.visit(nd, c);
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(nd.getInit(), isStrict, true, DeclKind.none);
Scope scope = null;
if (!lexicals.isEmpty()) {
scope = scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
}
visit(nd.getTest(), key, 1);
visit(nd.getUpdate(), key, 2);
/**
* If the 'for' statement declares lexical variables in its init, we have to handle it
* specially: while the variables are declared in the newly introduced scope, the initialiser
* expressions are evaluated in the outer scope. Since this differs from our normal handling
* of variable declarations, we have to treat the entire declaration inline instead of
* delegating to the normal visitor methods.
*/
if (!lexicals.isEmpty()) {
VariableDeclaration decl = (VariableDeclaration) nd.getInit();
Label declkey = visit((Statement) decl, new Context(key, 0, IdContext.varBind));
int idx = 0;
for (VariableDeclarator declarator : decl.getDeclarations()) {
Label declaratorKey =
visit((Expression) declarator, new Context(declkey, idx++, IdContext.varBind));
// the 'let' bound variable lives in the new scope
visit(declarator.getId(), declaratorKey, 0, IdContext.varDecl);
// but its initialiser does not
scopeManager.leaveScope();
visit(declarator.getInit(), declaratorKey, 1);
scopeManager.reenterScope(scope);
}
} else {
visit(nd.getInit(), key, 0);
}
contextManager.enterLoopStmt(nd);
visit(nd.getBody(), key, 3);
contextManager.leaveLoopStmt();
if (!lexicals.isEmpty()) scopeManager.leaveScope();
return key;
}
@Override
public Label visit(EnhancedForStatement nd, Context c) {
Label key = super.visit(nd, c);
DeclaredNames lexicals =
scopeManager.collectDeclaredNames(nd.getLeft(), isStrict, true, DeclKind.none);
visit(nd.getRight(), key, 1);
if (!lexicals.isEmpty()) {
scopeManager.enterScope(nd);
scopeManager.addNames(lexicals);
}
visit(nd.getLeft(), key, 0);
visit(nd.getDefaultValue(), key, -1);
contextManager.enterLoopStmt(nd);
visit(nd.getBody(), key, 2);
contextManager.leaveLoopStmt();
if (!lexicals.isEmpty()) scopeManager.leaveScope();
if (nd instanceof ForOfStatement && ((ForOfStatement) nd).isAwait())
trapwriter.addTuple("isForAwaitOf", key);
return key;
}
@Override
public Label visit(ArrayExpression nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getElements(), key, IdContext.varBind, 0);
trapwriter.addTuple("arraySize", key, nd.getElements().size());
return key;
}
@Override
public Label visit(ArrayPattern nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getElements(), key, c.idcontext, 0);
visit(nd.getRest(), key, -1, c.idcontext);
visitAll(nd.getDefaults(), key, IdContext.varBind, -2, -1);
trapwriter.addTuple("arraySize", key, nd.getElements().size());
return key;
}
@Override
public Label visit(ObjectPattern nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getProperties(), key, c.idcontext, 0);
visit(nd.getRest(), key, -1, c.idcontext);
return key;
}
@Override
public Label visit(ObjectExpression nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getProperties(), key, IdContext.varBind, 0);
return key;
}
@Override
public Label visit(Property nd, Context c) {
Label propkey = trapwriter.localID(nd);
int kind = nd.getKind().ordinal();
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("properties", propkey, c.parent, c.childIndex, kind, tostring);
locationManager.emitNodeLocation(nd, propkey);
visitAll(nd.getDecorators(), propkey, IdContext.varBind, -1, -1);
visit(nd.getKey(), propkey, 0, nd.isComputed() ? IdContext.varBind : IdContext.label);
visit(nd.getValue(), propkey, 1, c.idcontext);
visit(nd.getDefaultValue(), propkey, 2, IdContext.varBind);
if (nd.isComputed()) trapwriter.addTuple("isComputed", propkey);
if (nd.isMethod()) trapwriter.addTuple("isMethod", propkey);
return propkey;
}
@Override
public Label visit(IfStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTest(), key, 0);
visit(nd.getConsequent(), key, 1);
visit(nd.getAlternate(), key, 2);
return key;
}
@Override
public Label visit(ConditionalExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTest(), key, 0);
visit(nd.getConsequent(), key, 1);
visit(nd.getAlternate(), key, 2);
return key;
}
@Override
public Label visit(LabeledStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLabel(), key, 0, IdContext.label);
contextManager.enterLabeledStatement(nd);
visit(nd.getBody(), key, 1);
contextManager.leaveLabeledStatement(nd);
return key;
}
@Override
public Label visit(WithStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getObject(), key, 0);
visit(nd.getBody(), key, 1);
return key;
}
@Override
public Label visit(DoWhileStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTest(), key, 1);
contextManager.enterLoopStmt(nd);
visit(nd.getBody(), key, 0);
contextManager.leaveLoopStmt();
return key;
}
@Override
public Label visit(WhileStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTest(), key, 0);
contextManager.enterLoopStmt(nd);
visit(nd.getBody(), key, 1);
contextManager.leaveLoopStmt();
return key;
}
@Override
public Label visit(CatchClause nd, Context c) {
Label key = super.visit(nd, c);
scopeManager.enterScope(nd);
if (nd.getParam() != null) {
scopeManager.addNames(
scopeManager.collectDeclaredNames(nd.getParam(), isStrict, false, DeclKind.var));
visit(nd.getParam(), key, 0, IdContext.varDecl);
}
visit(nd.getGuard(), key, 2);
visit(nd.getBody(), key, 1);
scopeManager.leaveScope();
return key;
}
@Override
public Label visit(TryStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getBlock(), key, 0);
visitAll(nd.getAllHandlers(), key, IdContext.varBind, 1);
visit(nd.getFinalizer(), key, -1);
return key;
}
@Override
public Label visit(JumpStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLabel(), key, 0, IdContext.label);
Label targetKey = trapwriter.localID(contextManager.getTarget(nd));
trapwriter.addTuple("jumpTargets", key, targetKey);
return key;
}
@Override
public Label visit(ReturnStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0, IdContext.varBind);
return key;
}
@Override
public Label visit(ThrowStatement nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0, IdContext.varBind);
return key;
}
@Override
public Label visit(SequenceExpression nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getExpressions(), key, IdContext.varBind, 0);
return key;
}
@Override
public Label visit(ParenthesizedExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0, IdContext.varBind);
return key;
}
@Override
public Label visit(TaggedTemplateExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTag(), key, 0);
visit(nd.getQuasi(), key, 1);
visitAll(nd.getTypeArguments(), key, IdContext.typeBind, 2);
return key;
}
@Override
public Label visit(TemplateLiteral nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getChildren(), key, IdContext.varBind, 0);
return key;
}
@Override
public Label visit(TemplateElement nd, Context c) {
Label key = super.visit(nd, c);
String cooked;
if (nd.getCooked() == null) cooked = "";
else cooked = String.valueOf(nd.getCooked());
trapwriter.addTuple("literals", cooked, nd.getRaw(), key);
return key;
}
@Override
public Label visit(ClassDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", lbl);
}
if (nd.hasAbstractKeyword()) {
trapwriter.addTuple("isAbstractClass", lbl);
}
return visit(nd.getClassDef(), lbl, nd, false);
}
@Override
public Label visit(ClassExpression nd, Context c) {
Label lbl = super.visit(nd, c);
return visit(nd.getClassDef(), lbl, nd, true);
}
@Override
public Label visit(TypeParameter nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getId(), key, 0, IdContext.typeDecl);
visit(nd.getBound(), key, 1, IdContext.typeBind);
visit(nd.getDefault(), key, 2, IdContext.typeBind);
return key;
}
private Label visit(AClass ac, Label key, Node scopeNode, boolean isClassExpression) {
visitAll(ac.getDecorators(), key, IdContext.varBind, -2, -3);
// The identifier of a class declaration is visited before entering the
// class scope, since it must resolve to the enclosing block, not its own scope.
if (!isClassExpression) {
visit(ac.getId(), key, 0, IdContext.varAndTypeDecl);
}
if (ac.hasId() || ac.hasTypeParameters()) {
scopeManager.enterScope(scopeNode);
if (isClassExpression && ac.hasId()) {
scopeManager.addVariables(ac.getId().getName());
scopeManager.addTypeName(ac.getId().getName());
// Caveat: if the class name equals a type parameter name, the class name
// is shadowed. We don't model that; instead it will be seen as a type name
// that has two declarations (the class name and the type parameter).
}
for (TypeParameter tp : ac.getTypeParameters()) {
scopeManager.addTypeName(tp.getId().getName());
}
}
if (isClassExpression) {
visit(ac.getId(), key, 0, IdContext.varAndTypeDecl);
}
visitAll(ac.getTypeParameters(), key, IdContext.typeDecl, -3, -3);
visitAll(ac.getSuperInterfaces(), key, IdContext.typeBind, -1, -3);
visit(ac.getSuperClass(), key, 1);
MethodDefinition constructor = ac.getBody().getConstructor();
if (constructor == null) {
addDefaultConstructor(ac);
}
visit(ac.getBody(), key, 2);
if (ac.hasId() || ac.hasTypeParameters()) {
scopeManager.leaveScope();
}
emitNodeSymbol(ac, key);
return key;
}
private void emitNodeSymbol(INodeWithSymbol def, Label key) {
int symbol = def.getSymbol();
if (symbol != -1) {
Label symbolLabel = trapwriter.globalID("symbol;" + symbol);
trapwriter.addTuple("ast_node_symbol", key, symbolLabel);
}
}
@Override
public Label visit(NamespaceDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
emitNodeSymbol(nd, lbl);
IdContext context =
nd.isInstantiated() ? IdContext.varAndNamespaceDecl : IdContext.namespaceDecl;
visit(nd.getName(), lbl, -1, context);
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", lbl);
}
DeclaredNames hoistedVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, false, DeclKind.none);
DeclaredNames lexicalVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, true, DeclKind.none);
scopeManager.enterScope(nd);
scopeManager.addNames(hoistedVars);
scopeManager.addNames(lexicalVars);
contextManager.enterContainer(lbl);
visitAll(nd.getBody(), lbl);
contextManager.leaveContainer();
scopeManager.leaveScope();
if (nd.isInstantiated()) {
trapwriter.addTuple("isInstantiated", lbl);
}
return lbl;
}
/**
* Add a synthetic default constructor to {@code ac}: for classes without a superclass, the
* default constructor is {@code constructor() {}}, for those with a superclass, it is {@code
* constructor(...args) { super(...args); }}.
*/
private void addDefaultConstructor(AClass ac) {
ClassBody classBody = ac.getBody();
Position loc = classBody.getLoc().getStart();
// fake identifier `constructor`
SourceLocation idLoc = fakeLoc("constructor", loc);
Identifier id = new Identifier(idLoc, "constructor");
// fake body `{}` or `{ super(...args); }`
boolean hasSuperClass = ac.hasSuperClass();
SourceLocation bodyLoc = fakeLoc(hasSuperClass ? "{ super(...args); }" : "{}", loc);
BlockStatement body = new BlockStatement(bodyLoc, new ArrayList<Statement>());
if (hasSuperClass) {
Identifier argsRef = new Identifier(fakeLoc("args", loc), "args");
SpreadElement spreadArgs = new SpreadElement(fakeLoc("...args", loc), argsRef);
Super superExpr = new Super(fakeLoc("super", loc));
CallExpression superCall =
new CallExpression(
fakeLoc("super(...args)", loc),
superExpr,
new ArrayList<>(),
CollectionUtil.makeList(spreadArgs),
false,
false);
ExpressionStatement superCallStmt =
new ExpressionStatement(fakeLoc("super(...args);", loc), superCall);
body.getBody().add(superCallStmt);
}
// fake method definition `() {}` or `(...args) { super(...args); }`
List<Expression> params = new ArrayList<>();
if (hasSuperClass) {
Identifier argsDecl = new Identifier(fakeLoc("args", loc), "args");
RestElement restArgs = new RestElement(fakeLoc("...args", loc), argsDecl);
params.add(restArgs);
}
AFunction<BlockStatement> fndef =
new AFunction<>(
null,
params,
body,
false,
false,
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
null,
null,
AFunction.noOptionalParams);
String fnSrc = hasSuperClass ? "(...args) { super(...args); }" : "() {}";
SourceLocation fnloc = fakeLoc(fnSrc, loc);
FunctionExpression fn = new FunctionExpression(fnloc, fndef);
// fake constructor definition `constructor() {}`
// or `constructor(...args) { super(...args); }`
String ctorSrc =
hasSuperClass ? "constructor(...args) { super(...args); }" : "constructor() {}";
SourceLocation ctorloc = fakeLoc(ctorSrc, loc);
MethodDefinition ctor =
new MethodDefinition(ctorloc, DeclarationFlags.none, Kind.CONSTRUCTOR, id, fn);
classBody.addMember(ctor);
}
private SourceLocation fakeLoc(String src, Position loc) {
return new SourceLocation(src, loc, loc);
}
/** The constructors of all enclosing classes. */
private Stack<MethodDefinition> ctors = new Stack<>();
@Override
public Label visit(ClassBody nd, Context c) {
ctors.push(nd.getConstructor());
visitAll(nd.getBody(), c.parent, c.idcontext, c.childIndex);
visitAll(
nd.getConstructor().getParameterFields(),
c.parent,
c.idcontext,
c.childIndex + nd.getBody().size());
ctors.pop();
return c.parent;
}
private int getMethodKind(MethodDefinition nd) {
switch (nd.getKind()) {
case METHOD:
case CONSTRUCTOR:
return 0;
case GET:
return 1;
case SET:
return 2;
case FUNCTION_CALL_SIGNATURE:
return 4;
case CONSTRUCTOR_CALL_SIGNATURE:
return 5;
case INDEX_SIGNATURE:
return 6;
}
return 0;
}
private int getFieldKind(FieldDefinition nd) {
return nd.isParameterField() ? 9 : 8;
}
@Override
public Label visit(MemberDefinition<?> nd, Context c) {
Label methkey = trapwriter.localID(nd);
int kind;
if (nd instanceof MethodDefinition) {
kind = getMethodKind((MethodDefinition) nd);
} else {
kind = getFieldKind((FieldDefinition) nd);
}
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("properties", methkey, c.parent, c.childIndex, kind, tostring);
locationManager.emitNodeLocation(nd, methkey);
visitAll(nd.getDecorators(), methkey, IdContext.varBind, -1, -1);
// the name and initialiser expression of an instance field is evaluated as part of
// the constructor, so we adjust our syntactic context to reflect this
MethodDefinition ctor = null;
if (nd instanceof FieldDefinition && !nd.isStatic() && !ctors.isEmpty()) ctor = ctors.peek();
Label constructorKey = null;
if (ctor != null) {
constructorKey = trapwriter.localID(ctor.getValue());
contextManager.enterContainer(constructorKey);
}
visit(nd.getKey(), methkey, 0, nd.isComputed() ? IdContext.varBind : IdContext.label);
visit(nd.getValue(), methkey, 1, c.idcontext);
if (ctor != null) contextManager.leaveContainer();
if (nd instanceof MethodDefinition && !nd.isCallSignature() && !nd.isIndexSignature())
trapwriter.addTuple("isMethod", methkey);
// Emit tuples for isStatic, isAbstract, isComputed, etc
for (int i = 0; i < DeclarationFlags.numberOfFlags; ++i) {
if (DeclarationFlags.hasNthFlag(nd.getFlags(), i)) {
trapwriter.addTuple(DeclarationFlags.relationNames.get(i), methkey);
}
}
if (nd instanceof FieldDefinition) {
FieldDefinition field = (FieldDefinition) nd;
if (field.isParameterField() && constructorKey != null) {
trapwriter.addTuple(
"parameter_fields", methkey, constructorKey, field.getFieldParameterIndex());
} else {
visit(field.getTypeAnnotation(), methkey, 2, IdContext.typeBind);
}
}
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", methkey);
}
return methkey;
}
@Override
public Label visit(MetaProperty nd, Context c) {
return visit((Expression) nd, c);
}
@Override
public Label visit(ExportAllDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getSource(), lbl, 0);
return lbl;
}
@Override
public Label visit(ExportDefaultDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getDeclaration(), lbl, 0, IdContext.export);
return lbl;
}
@Override
public Label visit(ExportNamedDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getDeclaration(), lbl, -1);
visit(nd.getSource(), lbl, -2);
IdContext childContext =
nd.hasSource() ? IdContext.label :
nd.hasTypeKeyword() ? IdContext.typeOnlyExport :
IdContext.export;
visitAll(nd.getSpecifiers(), lbl, childContext, 0);
if (nd.hasTypeKeyword()) {
trapwriter.addTuple("hasTypeKeyword", lbl);
}
return lbl;
}
@Override
public Label visit(ExportSpecifier nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getLocal(), lbl, 0, c.idcontext);
visit(nd.getExported(), lbl, 1, IdContext.label);
return lbl;
}
@Override
public Label visit(ImportDeclaration nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getSource(), lbl, -1);
IdContext childContext = nd.hasTypeKeyword() ? IdContext.typeOnlyImport : IdContext.varAndTypeAndNamespaceDecl;
visitAll(nd.getSpecifiers(), lbl, childContext, 0);
emitNodeSymbol(nd, lbl);
if (nd.hasTypeKeyword()) {
trapwriter.addTuple("hasTypeKeyword", lbl);
}
return lbl;
}
@Override
public Label visit(ImportSpecifier nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getImported(), lbl, 0, IdContext.label);
visit(nd.getLocal(), lbl, 1, c.idcontext);
return lbl;
}
@Override
public Label visit(JSXElement nd, Context c) {
Label lbl = super.visit(nd, c);
JSXOpeningElement open = nd.getOpeningElement();
IJSXName name = open.getName();
/*
* Children of JSX elements are populated at the following indices:
*
* - -1: element name (omitted for fragments)
* - 0, 1, 2, ...: attributes
* - -2, -3, ...: body elements
*
* A spread attribute is represented as an attribute without
* a name, whose value is a spread element.
*/
visit(name, lbl, -1, isTagName(name) ? IdContext.label : IdContext.varBind);
visitAll(open.getAttributes(), lbl, IdContext.varBind, 0, 1);
visitAll(nd.getChildren(), lbl, IdContext.varBind, -2, -1);
return lbl;
}
/**
* A JSX element name is interpreted as an HTML tag name if it starts with a lower-case
* character or contains a dash.
*/
private boolean isTagName(IJSXName name) {
if (name instanceof JSXIdentifier) {
String id = ((JSXIdentifier) name).getName();
return Character.isLowerCase(id.charAt(0)) || id.contains("-");
}
return false;
}
@Override
public Label visit(JSXIdentifier nd, Context c) {
return visit((Identifier) nd, c);
}
@Override
public Label visit(JSXMemberExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getObject(), key, 0);
visit(nd.getName(), key, 1, IdContext.label);
return key;
}
@Override
public Label visit(JSXNamespacedName nd, Context c) {
Label lbl = super.visit(nd, c);
visit(nd.getNamespace(), lbl, 0, IdContext.label);
visit(nd.getName(), lbl, 1, IdContext.label);
return lbl;
}
@Override
public Label visit(JSXAttribute nd, Context c) {
Label propkey = trapwriter.localID(nd);
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("properties", propkey, c.parent, c.childIndex, 3, tostring);
locationManager.emitNodeLocation(nd, propkey);
visit(nd.getName(), propkey, 0, IdContext.label);
visit(nd.getValue(), propkey, 1, c.idcontext);
return propkey;
}
@Override
public Label visit(JSXSpreadAttribute nd, Context c) {
// We want to represent a spread attribute like `{...props}` as an anonymous attribute
// whose value is a spread expression `...props`. Hence we need two entities,
// one for the attribute and one for the spread expression, which both correspond
// to the same AST node. We achieve this by using a special label kind for the former
// to make the trap writer give it a different label
// first, make one entity for the attribute, and populate its entry
// in the `properties` table
Label propkey = trapwriter.localID(nd, "JSXSpreadAttribute");
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("properties", propkey, c.parent, c.childIndex, 3, tostring);
locationManager.emitNodeLocation(nd, propkey);
// now populate the spread expression, stripping off the surrounding
// braces for its tostring
tostring = tostring.substring(1, tostring.length() - 1).trim();
Label valkey = visit(nd, 66, tostring, new Context(propkey, 1, IdContext.varBind));
visit(nd.getArgument(), valkey, 0);
return propkey;
}
@Override
public Label visit(JSXExpressionContainer nd, Context c) {
return visit(nd.getExpression(), c.parent, c.childIndex);
}
@Override
public Label visit(JSXEmptyExpression nd, Context c) {
return visit(nd, 91, c);
}
@Override
public Label visit(AwaitExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArgument(), key, 0);
return key;
}
@Override
public Label visit(Decorator nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0);
return key;
}
@Override
public Label visit(BindExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getObject(), key, 0);
visit(nd.getCallee(), key, 1);
return key;
}
@Override
public Label visit(ImportWholeDeclaration nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLhs(), key, 0, IdContext.varAndTypeAndNamespaceDecl);
visit(nd.getRhs(), key, 1, IdContext.export);
return key;
}
@Override
public Label visit(ExportWholeDeclaration nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getRhs(), key, 0, IdContext.export);
return key;
}
@Override
public Label visit(ExternalModuleReference nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0);
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(DynamicImport nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getSource(), key, 0);
return key;
}
@Override
public Label visit(InterfaceDeclaration nd, Context c) {
Label key = super.visit(nd, c);
if (nd.hasTypeParameters()) {
scopeManager.enterScope(nd);
for (TypeParameter tp : nd.getTypeParameters()) {
scopeManager.addTypeName(tp.getId().getName());
}
}
visitAll(nd.getTypeParameters(), key, IdContext.typeBind, -2, -2);
visitAll(nd.getSuperInterfaces(), key, IdContext.typeBind, -1, -2);
visit(nd.getName(), key, 0, IdContext.typeDecl);
visitAll(nd.getBody(), key, IdContext.label, 2);
if (nd.hasTypeParameters()) {
scopeManager.leaveScope();
}
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(KeywordTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
trapwriter.addTuple("literals", nd.getKeyword(), nd.getKeyword(), key);
return key;
}
@Override
public Label visit(ArrayTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getElementType(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(UnionTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getElementTypes(), key, IdContext.typeBind, 0);
return key;
}
@Override
public Label visit(IndexedAccessTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getObjectType(), key, 0, IdContext.typeBind);
visit(nd.getIndexType(), key, 1, IdContext.typeBind);
return key;
}
@Override
public Label visit(IntersectionTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getElementTypes(), key, IdContext.typeBind, 0);
return key;
}
@Override
public Label visit(ParenthesizedTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getElementType(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(TupleTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getElementTypes(), key, IdContext.typeBind, 0);
return key;
}
@Override
public Label visit(UnaryTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getElementType(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(GenericTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTypeName(), key, -1, IdContext.typeBind);
visitAll(nd.getTypeArguments(), key, IdContext.typeBind, 0);
return key;
}
@Override
public Label visit(TypeofTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0, IdContext.varInTypeBind);
return key;
}
@Override
public Label visit(PredicateTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0, IdContext.varInTypeBind);
visit(nd.getTypeExpr(), key, 1, IdContext.typeBind);
if (nd.hasAssertsKeyword()) {
trapwriter.addTuple("hasAssertsKeyword", key);
}
return key;
}
@Override
public Label visit(InterfaceTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getBody(), key);
return key;
}
@Override
public Label visit(ExpressionWithTypeArguments nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, -1, IdContext.varBind);
visitAll(nd.getTypeArguments(), key, IdContext.typeBind, 0);
return key;
}
@Override
public Label visit(FunctionTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getFunction(), key, 0);
return key;
}
@Override
public Label visit(TypeAssertion nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0);
visit(nd.getTypeAnnotation(), key, 1, IdContext.typeBind);
return key;
}
@Override
public Label visit(MappedTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
scopeManager.enterScope(nd);
scopeManager.addTypeName(nd.getTypeParameter().getId().getName());
visit(nd.getTypeParameter(), key, 0, IdContext.typeDecl);
visit(nd.getElementType(), key, 1, IdContext.typeBind);
scopeManager.leaveScope();
return key;
}
@Override
public Label visit(TypeAliasDeclaration nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getId(), key, 0, IdContext.typeDecl);
if (nd.hasTypeParameters()) {
scopeManager.enterScope(nd);
for (TypeParameter tp : nd.getTypeParameters()) {
scopeManager.addTypeName(tp.getId().getName());
}
}
visitAll(nd.getTypeParameters(), key, IdContext.typeDecl, 2, 1);
visit(nd.getDefinition(), key, 1, IdContext.typeBind);
if (nd.hasTypeParameters()) {
scopeManager.leaveScope();
}
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(EnumDeclaration nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getId(), key, 0, IdContext.varAndTypeAndNamespaceDecl);
visitAll(nd.getDecorators(), key, IdContext.varBind, -1, -1);
scopeManager.enterScope(nd);
for (EnumMember member : nd.getMembers()) {
scopeManager.addVariables(member.getId().getName());
scopeManager.addTypeName(member.getId().getName());
}
visitAll(nd.getMembers(), key, IdContext.varAndTypeDecl, 1, 1);
scopeManager.leaveScope();
if (nd.isConst()) {
trapwriter.addTuple("isConstEnum", key);
}
if (nd.hasDeclareKeyword()) {
trapwriter.addTuple("hasDeclareKeyword", key);
}
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(EnumMember nd, Context c) {
Label key = trapwriter.localID(nd);
String tostring = lexicalExtractor.mkToString(nd);
trapwriter.addTuple("properties", key, c.parent, c.childIndex, 7, tostring);
locationManager.emitNodeLocation(nd, key);
visit(nd.getId(), key, 0, IdContext.varAndTypeDecl);
visit(nd.getInitializer(), key, 1, IdContext.varBind);
emitNodeSymbol(nd, key);
return key;
}
@Override
public Label visit(ExternalModuleDeclaration nd, Context c) {
Label key = super.visit(nd, c);
trapwriter.addTuple("hasDeclareKeyword", key);
visit(nd.getName(), key, -1, IdContext.label);
DeclaredNames hoistedVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, false, DeclKind.none);
DeclaredNames lexicalVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, true, DeclKind.none);
scopeManager.enterScope(nd);
scopeManager.addNames(hoistedVars);
scopeManager.addNames(lexicalVars);
contextManager.enterContainer(key);
visitAll(nd.getBody(), key);
contextManager.leaveContainer();
scopeManager.leaveScope();
return key;
}
@Override
public Label visit(ExportAsNamespaceDeclaration nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getId(), key, 0, IdContext.label);
return key;
}
@Override
public Label visit(DecoratorList nd, Context c) {
Label key = super.visit(nd, c);
visitAll(nd.getDecorators(), key, IdContext.varBind, 0);
return key;
}
@Override
public Label visit(GlobalAugmentationDeclaration nd, Context c) {
// It is possible for declarations in the global scope block to refer
// to types not declared in the global scope. For instance:
//
// interface I {}
// declare global {
// var x: I
// }
//
// At extraction time, we model this by introducing a scope for the block
// that has the same label as the global scope, but is otherwise a normal scope.
// The fake scope does not exist at the QL level, as it is indistinguishable
// from the global scope.
Label key = super.visit(nd, c);
trapwriter.addTuple("hasDeclareKeyword", key);
DeclaredNames hoistedVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, false, DeclKind.none);
DeclaredNames lexicalVars =
scopeManager.collectDeclaredNames(nd.getBody(), isStrict, true, DeclKind.none);
scopeManager.enterGlobalAugmentationScope();
scopeManager.addNames(hoistedVars);
scopeManager.addNames(lexicalVars);
contextManager.enterContainer(key);
visitAll(nd.getBody(), key);
contextManager.leaveContainer();
scopeManager.leaveScope();
return key;
}
@Override
public Label visit(NonNullAssertion nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getExpression(), key, 0);
return key;
}
@Override
public Label visit(ConditionalTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getCheckType(), key, 0, IdContext.typeBind);
Set<String> boundTypes = scopeManager.collectDeclaredInferTypes(nd.getExtendsType());
if (!boundTypes.isEmpty()) {
scopeManager.enterScope(nd);
scopeManager.addTypeNames(boundTypes);
}
visit(nd.getExtendsType(), key, 1, IdContext.typeBind);
visit(nd.getTrueType(), key, 2, IdContext.typeBind);
if (!boundTypes.isEmpty()) {
scopeManager.leaveScope();
}
visit(nd.getFalseType(), key, 3, IdContext.typeBind);
return key;
}
@Override
public Label visit(InferTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getTypeParameter(), key, 0, IdContext.typeDecl);
return key;
}
@Override
public Label visit(ImportTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getPath(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(OptionalTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getElementType(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(RestTypeExpr nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getArrayType(), key, 0, IdContext.typeBind);
return key;
}
@Override
public Label visit(XMLAttributeSelector nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getAttribute(), key, 0, IdContext.label);
return key;
}
@Override
public Label visit(XMLFilterExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1);
return key;
}
@Override
public Label visit(XMLQualifiedIdentifier nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1, nd.isComputed() ? IdContext.varBind : IdContext.label);
return key;
}
@Override
public Label visit(XMLDotDotExpression nd, Context c) {
Label key = super.visit(nd, c);
visit(nd.getLeft(), key, 0);
visit(nd.getRight(), key, 1, IdContext.label);
return key;
}
@Override
public Label visit(AssignmentPattern nd, Context c) {
additionalErrors.add(
new ParseError("Unexpected assignment pattern.", nd.getLoc().getStart()));
return super.visit(nd, c);
}
}
public List<ParseError> extract(
Node root, Platform platform, SourceType sourceType, int toplevelKind) {
lexicalExtractor.getMetrics().startPhase(ExtractionPhase.ASTExtractor_extract);
trapwriter.addTuple("toplevels", toplevelLabel, toplevelKind);
locationManager.emitNodeLocation(root, toplevelLabel);
V visitor = new V(platform, sourceType);
root.accept(visitor, null);
lexicalExtractor.getMetrics().stopPhase(ExtractionPhase.ASTExtractor_extract);
return visitor.additionalErrors;
}
}
| 74,504 | 34.143868 | 117 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/DeclaredNames.java | package com.semmle.js.extractor;
import java.util.LinkedHashSet;
import java.util.Set;
/** Names of variables, types, and namespaces declared in a particular scope. */
public class DeclaredNames {
private Set<String> variableNames;
private Set<String> typeNames;
private Set<String> namespaceNames;
public DeclaredNames() {
this.variableNames = new LinkedHashSet<String>();
this.typeNames = new LinkedHashSet<String>();
this.namespaceNames = new LinkedHashSet<String>();
}
public DeclaredNames(
Set<String> variableNames, Set<String> typeNames, Set<String> namespaceNames) {
this.variableNames = variableNames;
this.typeNames = typeNames;
this.namespaceNames = namespaceNames;
}
public boolean isEmpty() {
return variableNames.isEmpty() && typeNames.isEmpty() && namespaceNames.isEmpty();
}
public Set<String> getVariableNames() {
return variableNames;
}
public Set<String> getTypeNames() {
return typeNames;
}
public Set<String> getNamespaceNames() {
return namespaceNames;
}
}
| 1,063 | 24.95122 | 86 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/VirtualSourceRoot.java | package com.semmle.js.extractor;
import java.nio.file.Path;
public class VirtualSourceRoot {
private Path sourceRoot;
private Path virtualSourceRoot;
private Object lock = new Object();
public static final VirtualSourceRoot none = new VirtualSourceRoot(null, null);
public VirtualSourceRoot(Path sourceRoot, Path virtualSourceRoot) {
this.sourceRoot = sourceRoot;
this.virtualSourceRoot = virtualSourceRoot;
}
/**
* Returns the source root mirrored by {@link #getVirtualSourceRoot()} or <code>null</code> if no
* virtual source root exists.
*
* <p>When invoked from the AutoBuilder, this corresponds to the source root. When invoked from
* ODASA, there is no notion of source root, so this is always <code>null</code> in that context.
*/
public Path getSourceRoot() {
return sourceRoot;
}
/**
* Returns the virtual source root or <code>null</code> if no virtual source root exists.
*
* <p>The virtual source root is a directory hierarchy that mirrors the real source root, where
* dependencies are installed.
*/
public Path getVirtualSourceRoot() {
return virtualSourceRoot;
}
private static Path translate(Path oldRoot, Path newRoot, Path file) {
if (oldRoot == null || newRoot == null) return null;
Path relative = oldRoot.relativize(file);
if (relative.startsWith("..") || relative.isAbsolute()) return null;
return newRoot.resolve(relative);
}
public Path toVirtualFile(Path file) {
if (file.startsWith(virtualSourceRoot)) {
// 'qltest' creates a virtual source root inside the real source root.
// Make sure such files don't appear to be inside the real source root.
return null;
}
return translate(sourceRoot, virtualSourceRoot, file);
}
public Path fromVirtualFile(Path file) {
return translate(virtualSourceRoot, sourceRoot, file);
}
public Path getVirtualFileForSnippet(FileSnippet snippet, String extension) {
String basename =
snippet.getOriginalFile().getFileName()
+ ".snippet."
+ snippet.getLine()
+ "."
+ snippet.getColumn()
+ extension;
return toVirtualFile(snippet.getOriginalFile().resolveSibling(basename));
}
@Override
public String toString() {
return "[sourceRoot=" + sourceRoot + ", virtualSourceRoot=" + virtualSourceRoot + "]";
}
/**
* Gets the lock to use when writing to the virtual source root in a multi-threaded context.
*/
public Object getLock() {
return lock;
}
}
| 2,550 | 30.493827 | 99 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/HTMLExtractor.java | package com.semmle.js.extractor;
import java.io.File;
import java.nio.file.Path;
import java.util.regex.Pattern;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.parser.ParseError;
import com.semmle.util.data.StringUtil;
import com.semmle.util.io.WholeIO;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.CharacterReference;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.RowColumnVector;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTagType;
/** Extractor for handling HTML and XHTML files. */
public class HTMLExtractor implements IExtractor {
/** List of HTML attributes whose value is interpreted as JavaScript. */
private static final Pattern JS_ATTRIBUTE =
Pattern.compile(
"^on(abort|blur|change|(dbl)?click|error|focus|key(down|press|up)|load|mouse(down|move|out|over|up)|re(set|size)|select|submit|unload)$",
Pattern.CASE_INSENSITIVE);
private final ExtractorConfig config;
private final ExtractorState state;
public HTMLExtractor(ExtractorConfig config, ExtractorState state) {
this.config = config.withPlatform(Platform.WEB);
this.state = state;
}
@Override
public LoCInfo extract(TextualExtractor textualExtractor) {
LoCInfo result = new LoCInfo(0, 0);
Source src = new Source(textualExtractor.getSource());
src.setLogger(null);
ScopeManager scopeManager =
new ScopeManager(textualExtractor.getTrapwriter(), config.getEcmaVersion());
LocationManager locationManager = textualExtractor.getLocationManager();
/*
* Extract all JavaScript snippets appearing in (in-line) script elements and
* as attribute values.
*/
for (Element elt : src.getAllElements()) {
LoCInfo snippetLoC = null;
if (elt.getName().equals(HTMLElementName.SCRIPT)) {
SourceType sourceType = getScriptSourceType(elt, textualExtractor.getExtractedFile());
if (sourceType != null) {
// Jericho sometimes misparses empty elements, which will show up as start tags
// ending in "/"; we manually exclude these cases to avoid spurious syntax errors
if (elt.getStartTag().getTagContent().toString().trim().endsWith("/")) continue;
Segment content = elt.getContent();
String source = content.toString();
boolean isTypeScript = isTypeScriptTag(elt);
/*
* Script blocks in XHTML files may wrap (parts of) their code inside CDATA sections.
* We need to unwrap them in order not to confuse the JavaScript parser.
*
* Note that CDATA sections do not nest, so they can be detected by a regular expression.
*
* In order to preserve position information, we replace the CDATA section markers with
* an equivalent number of whitespace characters. This will yield surprising results
* for CDATA sections inside string literals, but those are likely to be rare.
*/
source = source.replace("<![CDATA[", " ").replace("]]>", " ");
if (!source.trim().isEmpty()) {
RowColumnVector contentStart = content.getRowColumnVector();
snippetLoC =
extractSnippet(
1,
config.withSourceType(sourceType),
scopeManager,
textualExtractor,
source,
contentStart.getRow(),
contentStart.getColumn(),
isTypeScript);
}
}
} else {
Attributes attributes = elt.getAttributes();
// attributes can be null for directives
if (attributes != null)
for (Attribute attr : attributes) {
// ignore empty attributes
if (attr.getValue() == null || attr.getValue().isEmpty()) continue;
String source = attr.getValue();
RowColumnVector valueStart = attr.getValueSegment().getRowColumnVector();
if (JS_ATTRIBUTE.matcher(attr.getName()).matches()) {
snippetLoC =
extractSnippet(
2,
config,
scopeManager,
textualExtractor,
source,
valueStart.getRow(),
valueStart.getColumn(),
false /* isTypeScript */);
} else if (source.startsWith("javascript:")) {
source = source.substring(11);
snippetLoC =
extractSnippet(
3,
config,
scopeManager,
textualExtractor,
source,
valueStart.getRow(),
valueStart.getColumn() + 11,
false /* isTypeScript */);
}
}
}
if (snippetLoC != null) result.add(snippetLoC);
}
// extract HTML elements if necessary.
if (config.getHtmlHandling().extractElements()) {
extractChildElements(src, locationManager);
for (Element elt : src.getAllElements()) {
if (isPlainElement(elt)) {
extractChildElements(elt, locationManager);
extractAttributes(elt, locationManager);
}
}
}
return result;
}
/**
* Deduce the {@link SourceType} with which the given <code>script</code> element should be
* extracted, returning <code>null</code> if it cannot be determined.
*/
private SourceType getScriptSourceType(Element script, File file) {
String scriptType = getAttributeValueLC(script, "type");
String scriptLanguage = getScriptLanguage(script);
SourceType fallbackSourceType = config.getSourceType();
if (file.getName().endsWith(".vue")) {
fallbackSourceType = SourceType.MODULE;
}
if (isTypeScriptTag(script)) return fallbackSourceType;
// if `type` and `language` are both either missing, contain the
// string "javascript", or if `type` is the string "text/jsx", this is a plain script
if ((scriptType == null || scriptType.contains("javascript") || "text/jsx".equals(scriptType))
&& (scriptLanguage == null || scriptLanguage.contains("javascript")))
// use default source type
return fallbackSourceType;
// if `type` is "text/babel", the source type depends on the `data-plugins` attribute
if ("text/babel".equals(scriptType)) {
String plugins = getAttributeValueLC(script, "data-plugins");
if (plugins != null && plugins.contains("transform-es2015-modules-umd")) {
return SourceType.MODULE;
}
return fallbackSourceType;
}
// if `type` is "module", extract as module
if ("module".equals(scriptType)) return SourceType.MODULE;
return null;
}
private String getScriptLanguage(Element script) {
String scriptLanguage = getAttributeValueLC(script, "language");
if (scriptLanguage == null) { // Vue templates use 'lang' instead of 'language'.
scriptLanguage = getAttributeValueLC(script, "lang");
}
return scriptLanguage;
}
private boolean isTypeScriptTag(Element script) {
String language = getScriptLanguage(script);
if ("ts".equals(language) || "typescript".equals(language)) return true;
String type = getAttributeValueLC(script, "type");
if (type != null && type.contains("typescript")) return true;
return false;
}
/**
* Get the value of attribute <code>attr</code> of element <code>elt</code> in lower case; if the
* attribute has no value, <code>null</code> is returned.
*/
private String getAttributeValueLC(Element elt, String attr) {
String val = elt.getAttributeValue(attr);
return val == null ? val : StringUtil.lc(val);
}
private LoCInfo extractSnippet(
int toplevelKind,
ExtractorConfig config,
ScopeManager scopeManager,
TextualExtractor textualExtractor,
String source,
int line,
int column,
boolean isTypeScript) {
if (isTypeScript) {
Path file = textualExtractor.getExtractedFile().toPath();
FileSnippet snippet = new FileSnippet(file, line, column, toplevelKind, config.getSourceType());
VirtualSourceRoot vroot = config.getVirtualSourceRoot();
// Vue files are special in that they can be imported as modules, and may only contain one <script> tag.
// For .vue files we omit the usual snippet decoration to ensure the TypeScript compiler can find it.
Path virtualFile =
file.getFileName().toString().endsWith(".vue")
? vroot.toVirtualFile(file.resolveSibling(file.getFileName() + ".ts"))
: vroot.getVirtualFileForSnippet(snippet, ".ts");
if (virtualFile != null) {
virtualFile = virtualFile.toAbsolutePath().normalize();
synchronized(vroot.getLock()) {
new WholeIO().strictwrite(virtualFile, source);
}
state.getSnippets().put(virtualFile, snippet);
}
return null; // LoC info is accounted for later
}
TrapWriter trapwriter = textualExtractor.getTrapwriter();
LocationManager locationManager = textualExtractor.getLocationManager();
LocationManager scriptLocationManager =
new LocationManager(
locationManager.getSourceFile(), trapwriter, locationManager.getFileLabel());
scriptLocationManager.setStart(line, column);
JSExtractor extractor = new JSExtractor(config);
try {
TextualExtractor tx =
new TextualExtractor(
trapwriter,
scriptLocationManager,
source,
config.getExtractLines(),
textualExtractor.getMetrics(),
textualExtractor.getExtractedFile());
return extractor.extract(tx, source, toplevelKind, scopeManager).snd();
} catch (ParseError e) {
e.setPosition(scriptLocationManager.translatePosition(e.getPosition()));
throw e.asUserError();
}
}
/**
* Is {@code elt} a plain HTML element (as opposed to a doctype declaration, comment, processing
* instruction, etc.)?
*/
private boolean isPlainElement(Element elt) {
return elt.getStartTag().getTagType() == StartTagType.NORMAL;
}
/** Is {@code elt} a CDATA element ? */
private boolean isCDataElement(Element elt) {
return elt.getStartTag().getTagType() == StartTagType.CDATA_SECTION;
}
/** Is {@code elt} an HTML comment? */
private boolean isComment(Element elt) {
return elt.getStartTag().getTagType() == StartTagType.COMMENT;
}
/**
* Populate the {@code xmlElements} relation recording information about all child elements of
* {@code parent}, which is either an {@link Element} or a {@link Source} (representing the HTML
* file itself).
*/
private void extractChildElements(Segment parent, LocationManager locationManager) {
TrapWriter trapWriter = locationManager.getTrapWriter();
Label fileLabel = locationManager.getFileLabel();
Label parentLabel = parent instanceof Source ? fileLabel : trapWriter.localID(parent);
int childIndex = 0;
Source source = parent.getSource();
int contentStart =
parent instanceof Element ? ((Element) parent).getStartTag().getEnd() : parent.getBegin();
int contentEnd;
if (parent instanceof Element && ((Element) parent).getEndTag() != null)
contentEnd = ((Element) parent).getEndTag().getBegin();
else contentEnd = parent.getEnd();
int prevChildEnd = contentStart;
for (Element child : parent.getChildElements()) {
childIndex +=
emitXmlChars(
source,
prevChildEnd,
child.getBegin(),
parentLabel,
childIndex,
false,
fileLabel,
locationManager);
if (isCDataElement(child)) {
// treat CDATA sections as text
childIndex +=
emitXmlChars(
source,
child.getBegin() + "<![CDATA[".length(),
child.getEnd() - "]]>".length(),
parentLabel,
childIndex,
true,
fileLabel,
locationManager);
}
if (isPlainElement(child)) {
String childName = child.getName();
Label childLabel = trapWriter.localID(child);
trapWriter.addTuple(
"xmlElements", childLabel, childName, parentLabel, childIndex++, fileLabel);
emitLocation(child, childLabel, locationManager);
}
if (config.getHtmlHandling().extractComments() && isComment(child)) {
Label childLabel = trapWriter.localID(child);
trapWriter.addTuple("xmlComments", childLabel, child.toString(), parentLabel, fileLabel);
emitLocation(child, childLabel, locationManager);
}
prevChildEnd = child.getEnd();
}
emitXmlChars(
source,
prevChildEnd,
contentEnd,
parentLabel,
childIndex,
false,
fileLabel,
locationManager);
}
/**
* Populate the {@code xmlAttrs} relation recording information about all attributes of {@code
* elt}.
*/
private void extractAttributes(Element elt, LocationManager locationManager) {
TrapWriter trapWriter = locationManager.getTrapWriter();
Label fileLabel = locationManager.getFileLabel();
Label eltLabel = trapWriter.localID(elt);
Attributes attributes = elt.getAttributes();
// attributes can be null for directives
if (attributes == null) return;
int i = 0;
for (Attribute attr : attributes) {
String attrName = attr.getName();
String attrValue = attr.getValue() == null ? "" : attr.getValue();
Label attrLabel = trapWriter.localID(attr);
trapWriter.addTuple("xmlAttrs", attrLabel, eltLabel, attrName, attrValue, i++, fileLabel);
emitLocation(attr, attrLabel, locationManager);
}
}
/**
* Record the location of {@code s}, which is either an {@link Element} or an {@code Attribute}.
*/
private void emitLocation(Segment s, Label label, LocationManager locationManager) {
TrapWriter trapWriter = locationManager.getTrapWriter();
Source src = s.getSource();
int so = s.getBegin(), eo = s.getEnd() - 1;
int sl = src.getRow(so), sc = src.getColumn(so);
int el = src.getRow(eo), ec = src.getColumn(eo);
Label loc = locationManager.emitLocationsDefault(sl, sc, el, ec);
trapWriter.addTuple("xmllocations", label, loc);
}
/**
* If {@code textEnd} is greater than {@code textBegin}, extract all characters in that range as
* HTML text, populating {@code xmlChars} and make it the {@code i}th child of {@code
* parentLabel}.
*
* @return 1 if text was extractod, 0 otherwise
*/
private int emitXmlChars(
Source src,
int textBegin,
int textEnd,
Label parentLabel,
int id,
boolean isCData,
Label fileLabel,
LocationManager locationManager) {
if (!config.getHtmlHandling().extractText()) {
return 0;
}
if (textBegin >= textEnd) {
return 0;
}
TrapWriter trapWriter = locationManager.getTrapWriter();
Segment s = new Segment(src, textBegin, textEnd);
int so = s.getBegin(), eo = s.getEnd() - 1;
String rawText = s.toString();
if (!isCData) {
// expand entities. Note that `rawText` no longer spans the start/end region.
rawText = CharacterReference.decode(rawText, false);
}
Label label = trapWriter.freshLabel();
trapWriter.addTuple("xmlChars", label, rawText, parentLabel, id, isCData ? 1 : 0, fileLabel);
int sl = src.getRow(so), sc = src.getColumn(so);
int el = src.getRow(eo), ec = src.getColumn(eo);
Label loc = locationManager.emitLocationsDefault(sl, sc, el, ec);
trapWriter.addTuple("xmllocations", label, loc);
return 1;
}
}
| 16,247 | 37.051522 | 147 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ExtractionMetrics.java | package com.semmle.js.extractor;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Stack;
/** Metrics for the (single-threaded) extraction of a single file. */
public class ExtractionMetrics {
/**
* The phase of the extraction that should be measured time for.
*
* <p>Convention: the enum names have the format <code>{ClassName}_{MethodName}</code>, and should
* identify the methods they correspond to.
*/
public enum ExtractionPhase {
ASTExtractor_extract(0),
CFGExtractor_extract(1),
FileExtractor_extractContents(2),
JSExtractor_extract(3),
JSParser_parse(4),
LexicalExtractor_extractLines(5),
LexicalExtractor_extractTokens(6),
TypeScriptASTConverter_convertAST(7),
TypeScriptParser_talkToParserWrapper(8);
/** The id used in the database for the time spent performing this phase of the extraction. */
final int dbschemeId;
ExtractionPhase(int dbschemeId) {
this.dbschemeId = dbschemeId;
}
}
/** The cache file, if any. */
private File cacheFile;
/** True iff the extraction of this file reuses an existing trap cache file. */
private boolean canReuseCacheFile;
/** The cumulative CPU-time spent in each extraction phase so far. */
private final long[] cpuTimes = new long[ExtractionPhase.values().length];
/** The label for the file that is being extracted. */
private Label fileLabel;
/** The number of UTF16 code units in the file that is being extracted. */
private int length;
/** The previous time a CPU-time measure was performed. */
private long previousCpuTime;
/** The previous time a wallclock-time measure was performed. */
private long previousWallclockTime;
/** The extraction phase stack. */
private final Stack<ExtractionPhase> stack = new Stack<>();
/** The current thread, used for measuring CPU-time. */
private final ThreadMXBean thread = ManagementFactory.getThreadMXBean();
/** The cumulative wallclock-time spent in each extraction phase so far. */
private final long[] wallclockTimes = new long[ExtractionPhase.values().length];
/**
* True iff extraction metrics could not be obtained for this file (due to an unforeseen error
* that should not prevent the ordinary extraction from succeeding).
*/
private boolean timingsFailed;
/**
* Writes the data metrics to a trap file. Note that this makes the resulting trap file content
* non-deterministic.
*/
public void writeDataToTrap(TrapWriter trapwriter) {
trapwriter.addTuple(
"extraction_data",
fileLabel,
cacheFile != null ? cacheFile.getAbsolutePath() : "",
canReuseCacheFile,
length);
}
/**
* Writes the timing metrics to a trap file. Note that this makes the resulting trap file content
* non-deterministic.
*/
public void writeTimingsToTrap(TrapWriter trapwriter) {
if (!stack.isEmpty()) {
failTimings(
String.format(
"Could not properly record extraction times for %s. (stack = %s)%n",
fileLabel, stack.toString()));
}
if (!timingsFailed) {
for (int i = 0; i < ExtractionPhase.values().length; i++) {
trapwriter.addTuple("extraction_time", fileLabel, i, 0, (float) cpuTimes[i]);
trapwriter.addTuple("extraction_time", fileLabel, i, 1, (float) wallclockTimes[i]);
}
}
}
private void failTimings(String msg) {
System.err.println(msg);
System.err.flush();
this.timingsFailed = true;
}
private void incrementCurrentTimer() {
long nowWallclock = System.nanoTime();
long nowCpu = thread.getCurrentThreadCpuTime();
if (!stack.isEmpty()) {
// increment by the time elapsed
wallclockTimes[stack.peek().dbschemeId] += nowWallclock - previousWallclockTime;
cpuTimes[stack.peek().dbschemeId] += nowCpu - previousCpuTime;
}
// update the running clock
previousWallclockTime = nowWallclock;
previousCpuTime = nowCpu;
}
public void setCacheFile(File cacheFile) {
this.cacheFile = cacheFile;
}
public void setCanReuseCacheFile(boolean canReuseCacheFile) {
this.canReuseCacheFile = canReuseCacheFile;
}
public void setFileLabel(Label fileLabel) {
this.fileLabel = fileLabel;
}
public void setLength(int length) {
this.length = length;
}
public void startPhase(ExtractionPhase event) {
incrementCurrentTimer();
stack.push(event);
}
public void stopPhase(
ExtractionPhase
event /* technically not needed, but useful for documentation and consistency checking */) {
if (stack.isEmpty()) {
failTimings(
String.format(
"Inconsistent extraction time recording: trying to stop timer %s, but no timer is running",
event));
return;
}
if (stack.peek() != event) {
failTimings(
String.format(
"Inconsistent extraction time recording: trying to stop timer %s, but current timer is: %s",
event, stack.peek()));
return;
}
incrementCurrentTimer();
stack.pop();
}
}
| 5,256 | 30.291667 | 106 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/LocationManager.java | package com.semmle.js.extractor;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.SourceElement;
import com.semmle.util.files.FileUtil;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class handles location information; in particular, it translates locations reported by the
* various parsers to absolute source file locations.
*/
public class LocationManager {
private final File sourceFile;
private final TrapWriter trapWriter;
private final Label fileLabel;
private int startColumn;
private int startLine;
private final Set<String> locationDefaultEmitted = new LinkedHashSet<String>();
private String hasLocation = "hasLocation";
public LocationManager(File sourceFile, TrapWriter trapWriter, Label fileLabel) {
this.sourceFile = sourceFile;
this.trapWriter = trapWriter;
this.fileLabel = fileLabel;
this.startLine = 1;
this.startColumn = 1;
}
public File getSourceFile() {
return sourceFile;
}
public String getSourceFileExtension() {
return FileUtil.extension(sourceFile);
}
public TrapWriter getTrapWriter() {
return trapWriter;
}
public Label getFileLabel() {
return fileLabel;
}
public int getStartLine() {
return startLine;
}
public int getStartColumn() {
return startColumn;
}
public void setStart(int line, int column) {
startLine = line;
startColumn = column;
}
public void setHasLocationTable(String hasLocation) {
this.hasLocation = hasLocation;
}
/**
* Emit location information for an AST node. The node's location is translated from the parser's
* 0-based column numbering scheme with exclusive offsets into our 1-based scheme with inclusive
* end-offsets and then emitted as a snippet location.
*/
public void emitNodeLocation(SourceElement nd, Label lbl) {
int sl = nd.getLoc().getStart().getLine(),
sc = nd.getLoc().getStart().getColumn(),
el = nd.getLoc().getEnd().getLine(),
ec = nd.getLoc().getEnd().getColumn();
// adjust start column since the parser uses 0-based indexing
// (note: no adjustment needed for end column, since the parser also uses
// exclusive end columns)
sc++;
// standardise empty locations
if (el < sl || el == sl && ec < sc) {
el = sl;
ec = sc - 1;
}
emitSnippetLocation(lbl, sl, sc, el, ec);
}
/**
* Emit a relative location in the current snippet.
*
* @param lbl label to associate with the location
* @param sl start line (1-based)
* @param sc start column (1-based, inclusive)
* @param el end line (1-based)
* @param ec end column (1-based, inclusive)
*/
public void emitSnippetLocation(Label lbl, int sl, int sc, int el, int ec) {
Position start = translatePosition(new Position(sl, sc, -1));
Position end = translatePosition(new Position(el, ec, -1));
emitFileLocation(lbl, start.getLine(), start.getColumn(), end.getLine(), end.getColumn());
}
/** Emit an absolute location in the current file. No line or column adjustment is performed. */
public void emitFileLocation(Label lbl, int sl, int sc, int el, int ec) {
Label locLabel = emitLocationsDefault(sl, sc, el, ec);
trapWriter.addTuple(hasLocation, lbl, locLabel);
}
/**
* Emit an entry in the {@code locations_default} table. No line or column adjustment is
* performed.
*/
public Label emitLocationsDefault(int sl, int sc, int el, int ec) {
Label locLabel = trapWriter.location(fileLabel, sl, sc, el, ec);
if (locationDefaultEmitted.add(locLabel.toString()))
trapWriter.addTuple("locations_default", locLabel, fileLabel, sl, sc, el, ec);
return locLabel;
}
/**
* Emit location information for a parse error. These locations are special, since their reported
* line number can be one past the last line in the file. Our toolchain does not like such
* positions, so we artificially constrain the line number to be in an acceptable range.
*/
public void emitErrorLocation(Label lbl, Position pos, int numlines) {
int line = Math.max(1, Math.min(pos.getLine(), numlines));
int column = Math.max(1, pos.getColumn() + 1);
this.emitSnippetLocation(lbl, line, column, line, column);
}
/** Translate a relative position into an absolute position. */
public Position translatePosition(Position p) {
int line = p.getLine(), column = p.getColumn();
if (line == 1) column += startColumn - 1;
line += startLine - 1;
return new Position(line, column, -1);
}
}
| 4,648 | 31.971631 | 99 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ScopeManager.java | package com.semmle.js.extractor;
import com.semmle.js.ast.ArrayPattern;
import com.semmle.js.ast.BlockStatement;
import com.semmle.js.ast.CatchClause;
import com.semmle.js.ast.ClassBody;
import com.semmle.js.ast.ClassDeclaration;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.DoWhileStatement;
import com.semmle.js.ast.EnhancedForStatement;
import com.semmle.js.ast.ExportDefaultDeclaration;
import com.semmle.js.ast.ExportNamedDeclaration;
import com.semmle.js.ast.ForStatement;
import com.semmle.js.ast.FunctionDeclaration;
import com.semmle.js.ast.FunctionExpression;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.IfStatement;
import com.semmle.js.ast.ImportDeclaration;
import com.semmle.js.ast.ImportSpecifier;
import com.semmle.js.ast.LabeledStatement;
import com.semmle.js.ast.LetExpression;
import com.semmle.js.ast.LetStatement;
import com.semmle.js.ast.MemberDefinition;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.ObjectPattern;
import com.semmle.js.ast.Program;
import com.semmle.js.ast.Property;
import com.semmle.js.ast.SwitchCase;
import com.semmle.js.ast.SwitchStatement;
import com.semmle.js.ast.TryStatement;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.js.ast.VariableDeclarator;
import com.semmle.js.ast.WhileStatement;
import com.semmle.js.ast.WithStatement;
import com.semmle.js.extractor.ExtractorConfig.ECMAVersion;
import com.semmle.ts.ast.ArrayTypeExpr;
import com.semmle.ts.ast.ConditionalTypeExpr;
import com.semmle.ts.ast.EnumDeclaration;
import com.semmle.ts.ast.FunctionTypeExpr;
import com.semmle.ts.ast.GenericTypeExpr;
import com.semmle.ts.ast.ITypeExpression;
import com.semmle.ts.ast.ImportWholeDeclaration;
import com.semmle.ts.ast.IndexedAccessTypeExpr;
import com.semmle.ts.ast.InferTypeExpr;
import com.semmle.ts.ast.InterfaceDeclaration;
import com.semmle.ts.ast.InterfaceTypeExpr;
import com.semmle.ts.ast.IntersectionTypeExpr;
import com.semmle.ts.ast.NamespaceDeclaration;
import com.semmle.ts.ast.ParenthesizedTypeExpr;
import com.semmle.ts.ast.PredicateTypeExpr;
import com.semmle.ts.ast.TupleTypeExpr;
import com.semmle.ts.ast.TypeAliasDeclaration;
import com.semmle.ts.ast.UnionTypeExpr;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Class for maintaining scoping information during extraction. */
public class ScopeManager {
public static class Scope {
private final Scope outer;
private final Label scopeLabel;
private final HashMap<String, Label> variableBindings = new LinkedHashMap<String, Label>();
private final HashMap<String, Label> typeBindings = new LinkedHashMap<String, Label>();
private final HashMap<String, Label> namespaceBindings = new LinkedHashMap<String, Label>();
public Scope(Scope outer, Label scopeLabel) {
this.outer = outer;
this.scopeLabel = scopeLabel;
}
public Label lookupVariable(String name) {
Label l = variableBindings.get(name);
if (l == null && outer != null) return outer.lookupVariable(name);
return l;
}
public Label lookupType(String name) {
Label l = typeBindings.get(name);
if (l == null && outer != null) return outer.lookupType(name);
return l;
}
public Label lookupNamespace(String name) {
Label l = namespaceBindings.get(name);
if (l == null && outer != null) return outer.lookupNamespace(name);
return l;
}
}
private final TrapWriter trapWriter;
private Scope curScope;
private final Scope toplevelScope;
private final ECMAVersion ecmaVersion;
private final Set<String> implicitGlobals = new LinkedHashSet<String>();
public ScopeManager(TrapWriter trapWriter, ECMAVersion ecmaVersion) {
this.trapWriter = trapWriter;
this.toplevelScope = enterScope(0, trapWriter.globalID("global_scope"), null);
this.ecmaVersion = ecmaVersion;
}
/**
* Enter a new scope.
*
* @param scopeKind the numeric scope kind
* @param scopeLabel the label of the scope itself
* @param scopeNodeLabel the label of the AST node inducing this scope; may be null
*/
public Scope enterScope(int scopeKind, Label scopeLabel, Label scopeNodeLabel) {
Label outerScopeLabel = curScope == null ? null : curScope.scopeLabel;
curScope = new Scope(curScope, scopeLabel);
trapWriter.addTuple("scopes", curScope.scopeLabel, scopeKind);
if (scopeNodeLabel != null)
trapWriter.addTuple("scopenodes", scopeNodeLabel, curScope.scopeLabel);
if (outerScopeLabel != null)
trapWriter.addTuple("scopenesting", curScope.scopeLabel, outerScopeLabel);
return curScope;
}
/** Enter the scope induced by a given AST node. */
public Scope enterScope(Node scopeNode) {
return enterScope(
scopeKinds.get(scopeNode.getType()),
trapWriter.freshLabel(),
trapWriter.localID(scopeNode));
}
/**
* Enters a scope for a block of form <tt>declare global { ... }</tt>.
*
* <p>Declarations in this block will contribute to the global scope, but references can still be
* resolved in the scope enclosing the declaration itself. The scope itself does not have its own
* label and will thus not exist at the QL level.
*/
public void enterGlobalAugmentationScope() {
curScope = new Scope(curScope, toplevelScope.scopeLabel);
}
/** Re-enter a scope that was previously established. */
public Scope reenterScope(Scope scope) {
return curScope = scope;
}
/** Leave the innermost scope. */
public void leaveScope() {
curScope = curScope.outer;
}
public Scope getToplevelScope() {
return toplevelScope;
}
private static final Map<String, Integer> scopeKinds = new LinkedHashMap<String, Integer>();
static {
scopeKinds.put("Program", 0);
scopeKinds.put("FunctionDeclaration", 1);
scopeKinds.put("FunctionExpression", 1);
scopeKinds.put("ArrowFunctionExpression", 1);
scopeKinds.put("CatchClause", 2);
scopeKinds.put("Module", 3);
scopeKinds.put("BlockStatement", 4);
scopeKinds.put("SwitchStatement", 4);
scopeKinds.put("ForStatement", 5);
scopeKinds.put("ForInStatement", 6);
scopeKinds.put("ForOfStatement", 6);
scopeKinds.put("ComprehensionBlock", 7);
scopeKinds.put("LetStatement", 4);
scopeKinds.put("LetExpression", 4);
scopeKinds.put("ClassExpression", 8);
scopeKinds.put("NamespaceDeclaration", 9);
scopeKinds.put("ClassDeclaration", 10);
scopeKinds.put("InterfaceDeclaration", 11);
scopeKinds.put("TypeAliasDeclaration", 12);
scopeKinds.put("MappedTypeExpr", 13);
scopeKinds.put("EnumDeclaration", 14);
scopeKinds.put("ExternalModuleDeclaration", 15);
scopeKinds.put("ConditionalTypeExpr", 16);
}
/**
* Get the label for a given variable in the current scope; if it cannot be found, add it to the
* global scope.
*/
public Label getVarKey(String name) {
Label lbl = curScope.lookupVariable(name);
if (lbl == null) {
lbl = addVariable(name, toplevelScope);
implicitGlobals.add(name);
}
return lbl;
}
/**
* Get the label for a given type in the current scope; or {@code null} if it cannot be found
* (unlike variables, there are no implicitly global type names).
*/
public Label getTypeKey(String name) {
return curScope.lookupType(name);
}
/**
* Get the label for a given namespace in the current scope; or {@code null} if it cannot be found
* (unlike variables, there are no implicitly global namespace names).
*/
public Label getNamespaceKey(String name) {
return curScope.lookupNamespace(name);
}
/** Add a variable to a given scope. */
private Label addVariable(String name, Scope scope) {
Label key = trapWriter.globalID("var;{" + name + "};{" + scope.scopeLabel + "}");
scope.variableBindings.put(name, key);
trapWriter.addTuple("variables", key, name, scope.scopeLabel);
return key;
}
/** Add the given list of variables to the current scope. */
public void addVariables(Iterable<String> names) {
for (String name : names) addVariable(name, curScope);
}
/** Convenience wrapper for {@link #addVariables(Iterable)}. */
public void addVariables(String... names) {
addVariables(Arrays.asList(names));
}
/** Add a type name to a given scope. */
private Label addTypeName(String name, Scope scope) {
Label key = trapWriter.globalID("local_type_name;{" + name + "};{" + scope.scopeLabel + "}");
scope.typeBindings.put(name, key);
trapWriter.addTuple("local_type_names", key, name, scope.scopeLabel);
return key;
}
/** Add a type name to the current scope. */
public Label addTypeName(String name) {
return addTypeName(name, curScope);
}
/** Add the given list of type names to the current scope. */
public void addTypeNames(Iterable<String> names) {
for (String name : names) addTypeName(name, curScope);
}
/** Adds a namespace name to the given scope. */
private Label addNamespaceName(String name, Scope scope) {
Label key =
trapWriter.globalID("local_namespace_name;{" + name + "};{" + scope.scopeLabel + "}");
scope.namespaceBindings.put(name, key);
trapWriter.addTuple("local_namespace_names", key, name, scope.scopeLabel);
return key;
}
/** Add the given list of namespace names to the current scope. */
public void addNamespaceNames(Iterable<String> names) {
for (String name : names) addNamespaceName(name, curScope);
}
/** Add the given list of variables to the current scope, returning the key for the last one. */
public void addNames(DeclaredNames names) {
addVariables(names.getVariableNames());
addTypeNames(names.getTypeNames());
addNamespaceNames(names.getNamespaceNames());
}
/** Does the current scope declare the given variable? */
public boolean declaredInCurrentScope(String name) {
return curScope.variableBindings.containsKey(name);
}
/** True if a declaration of 'name' is in scope, not counting implicit globals. */
public boolean isStrictlyInScope(String name) {
for (Scope scope = curScope; scope != null; scope = scope.outer) {
if (scope.variableBindings.containsKey(name)
&& !(scope == toplevelScope && implicitGlobals.contains(name))) {
return true;
}
}
return false;
}
public static class DeclKind {
public static final int var = 1 << 0;
public static final int type = 1 << 1;
public static final int namespace = 1 << 2;
public static final int none = 0;
public static final int varAndType = var | type;
public static final int varAndNamespace = var | namespace;
public static final int all = var | type | namespace;
public static boolean isVariable(int kind) {
return (kind & var) != 0;
}
public static boolean isType(int kind) {
return (kind & type) != 0;
}
public static boolean isNamespace(int kind) {
return (kind & namespace) != 0;
}
}
/**
* Collect all local variables, types, and namespaces declared in the given subtree. For
* convenience, 'subtree' is also allowed to be an array of subtrees, in which case all its
* elements are considered in turn.
*
* <p>{@code isStrict} indicates whether the subtree appears in strict-mode code (which influences
* the scoping of function declarations).
*
* <p>If 'blockscope' is true, only block-scoped declarations are considered, and traversal stops
* at block scope boundaries. Otherwise, only hoisted declarations are considered, and traversal
* stops at nested functions.
*
* <p>If 'declKind' is not {@link DeclKind#none}, then 'subtree' itself should be considered to be
* a declaration of the kind(s) specified.
*/
public DeclaredNames collectDeclaredNames(
INode subtree, boolean isStrict, boolean blockscope, int declKind) {
return collectDeclaredNames(Collections.singletonList(subtree), isStrict, blockscope, declKind);
}
public DeclaredNames collectDeclaredNames(
List<? extends INode> subforest,
final boolean isStrict,
final boolean blockscope,
final int declKind) {
final Set<String> variableNames = new LinkedHashSet<String>();
final Set<String> typeNames = new LinkedHashSet<String>();
final Set<String> namespaceNames = new LinkedHashSet<String>();
new DefaultVisitor<Void, Void>() {
private int declKind;
private Void visit(INode nd) {
return visit(nd, DeclKind.none);
}
private Void visit(List<? extends INode> nds) {
return rec(nds, DeclKind.none);
}
private Void visit(INode nd, int declKind) {
if (nd != null) {
int oldDeclKind = this.declKind;
this.declKind = declKind;
nd.accept(this, null);
this.declKind = oldDeclKind;
}
return null;
}
private Void rec(List<? extends INode> nds, int declKind) {
if (nds != null) for (INode nd : nds) visit(nd, declKind);
return null;
}
// this is where we actually process declarations
@Override
public Void visit(Identifier nd, Void v) {
if (DeclKind.isVariable(declKind)) variableNames.add(nd.getName());
if (DeclKind.isType(declKind)) typeNames.add(nd.getName());
if (DeclKind.isNamespace(declKind)) namespaceNames.add(nd.getName());
return null;
}
// cases where we turn on the 'declKind' flags
@Override
public Void visit(FunctionDeclaration nd, Void v) {
if (nd.hasDeclareKeyword()) return null;
// strict mode functions are block-scoped, non-strict mode ones aren't
if (blockscope == isStrict) visit(nd.getId(), DeclKind.var);
return null;
}
@Override
public Void visit(ClassDeclaration nd, Void c) {
if (nd.hasDeclareKeyword()) return null;
if (blockscope) visit(nd.getClassDef().getId(), DeclKind.varAndType);
return null;
}
@Override
public Void visit(VariableDeclarator nd, Void v) {
return visit(nd.getId(), DeclKind.var);
}
@Override
public Void visit(InterfaceDeclaration nd, Void c) {
if (blockscope) visit(nd.getName(), DeclKind.type);
return null;
}
// cases where we stop traversal for block scoping
@Override
public Void visit(BlockStatement nd, Void v) {
if (!blockscope) visit(nd.getBody());
return null;
}
@Override
public Void visit(SwitchStatement nd, Void v) {
if (!blockscope) visit(nd.getCases());
return null;
}
@Override
public Void visit(ForStatement nd, Void v) {
if (!blockscope) {
visit(nd.getInit());
visit(nd.getBody());
}
return null;
}
@Override
public Void visit(EnhancedForStatement nd, Void v) {
if (!blockscope) {
visit(nd.getLeft());
visit(nd.getBody());
}
return null;
}
@Override
public Void visit(VariableDeclaration nd, Void v) {
if (nd.hasDeclareKeyword()) return null;
// in block scoping mode, only process 'let'; in non-block scoping
// mode, only process non-'let'
if (blockscope == nd.isBlockScoped(ecmaVersion)) visit(nd.getDeclarations());
return null;
}
@Override
public Void visit(LetExpression nd, Void v) {
if (blockscope) visit(nd.getHead());
return null;
}
@Override
public Void visit(LetStatement nd, Void v) {
if (blockscope) visit(nd.getHead());
return null;
}
@Override
public Void visit(Property nd, Void v) {
// properties only give rise to declarations if they are part of an object pattern
if (DeclKind.isVariable(declKind)) visit(nd.getValue(), DeclKind.var);
return null;
}
@Override
public Void visit(ClassBody nd, Void c) {
if (!blockscope) visit(nd.getBody());
return null;
}
@Override
public Void visit(NamespaceDeclaration nd, Void c) {
if (blockscope) return null;
boolean hasVariable = nd.isInstantiated() && !nd.hasDeclareKeyword();
visit(nd.getName(), hasVariable ? DeclKind.varAndNamespace : DeclKind.namespace);
return null;
}
// straightforward recursive cases
@Override
public Void visit(ArrayPattern nd, Void v) {
rec(nd.getElements(), declKind);
return visit(nd.getRest(), declKind);
}
@Override
public Void visit(ObjectPattern nd, Void v) {
rec(nd.getProperties(), declKind);
return visit(nd.getRest(), declKind);
}
@Override
public Void visit(IfStatement nd, Void v) {
visit(nd.getConsequent());
return visit(nd.getAlternate());
}
@Override
public Void visit(LabeledStatement nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(WithStatement nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(WhileStatement nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(DoWhileStatement nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(Program nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(TryStatement nd, Void v) {
visit(nd.getBlock());
visit(nd.getHandler());
visit(nd.getGuardedHandlers());
return visit(nd.getFinalizer());
}
@Override
public Void visit(CatchClause nd, Void v) {
return visit(nd.getBody());
}
@Override
public Void visit(SwitchCase nd, Void v) {
return visit(nd.getConsequent());
}
@Override
public Void visit(ExportDefaultDeclaration nd, Void c) {
return visit(nd.getDeclaration());
}
@Override
public Void visit(ExportNamedDeclaration nd, Void c) {
return visit(nd.getDeclaration());
}
@Override
public Void visit(ImportDeclaration nd, Void c) {
return visit(nd.getSpecifiers());
}
@Override
public Void visit(ImportSpecifier nd, Void c) {
return visit(nd.getLocal(), DeclKind.all);
}
@Override
public Void visit(ImportWholeDeclaration nd, Void c) {
return visit(nd.getLhs(), DeclKind.all);
}
@Override
public Void visit(EnumDeclaration nd, Void c) {
if (!blockscope) return null;
// Enums always occupy a place in all three declaration spaces.
// In some contexts it is a compilation error to reference the enum name
// (e.g. a const enum used as namespace), but we do not need to model this
// in the scope analysis.
return visit(nd.getId(), DeclKind.all);
}
@Override
public Void visit(TypeAliasDeclaration nd, Void c) {
if (!blockscope) return null;
return visit(nd.getId(), DeclKind.type);
}
}.rec(subforest, declKind);
return new DeclaredNames(variableNames, typeNames, namespaceNames);
}
public Set<String> collectDeclaredInferTypes(ITypeExpression expr) {
final Set<String> result = new LinkedHashSet<>();
expr.accept(
new DefaultVisitor<Void, Void>() {
@Override
public Void visit(InferTypeExpr nd, Void c) {
// collect all the names declared by `infer R` types.
result.add(nd.getTypeParameter().getId().getName());
return null;
}
@Override
public Void visit(ConditionalTypeExpr nd, Void c) {
// Note: inhibit traversal into condition, since variables declared in the
// condition are bound to the inner conditional expression.
nd.getTrueType().accept(this, c);
nd.getFalseType().accept(this, c);
return null;
}
@Override
public Void visit(ArrayTypeExpr nd, Void c) {
return nd.getElementType().accept(this, c);
}
@Override
public Void visit(FunctionTypeExpr nd, Void c) {
return nd.getFunction().accept(this, c);
}
@Override
public Void visit(FunctionExpression nd, Void c) {
if (nd.getReturnType() != null) {
nd.getReturnType().accept(this, c);
}
for (ITypeExpression paramType : nd.getParameterTypes()) {
paramType.accept(this, c);
}
// note: `infer` types may not occur in type parameter bounds.
return null;
}
@Override
public Void visit(GenericTypeExpr nd, Void c) {
for (ITypeExpression typeArg : nd.getTypeArguments()) {
typeArg.accept(this, c);
}
return null;
}
@Override
public Void visit(IndexedAccessTypeExpr nd, Void c) {
nd.getObjectType().accept(this, null);
nd.getIndexType().accept(this, null);
return null;
}
@Override
public Void visit(InterfaceTypeExpr nd, Void c) {
for (MemberDefinition<?> member : nd.getBody()) {
member.accept(this, null);
}
return null;
}
@Override
public Void visit(IntersectionTypeExpr nd, Void c) {
for (ITypeExpression type : nd.getElementTypes()) {
type.accept(this, null);
}
return null;
}
@Override
public Void visit(PredicateTypeExpr nd, Void c) {
return nd.getTypeExpr().accept(this, c);
}
@Override
public Void visit(ParenthesizedTypeExpr nd, Void c) {
return nd.getElementType().accept(this, c);
}
@Override
public Void visit(TupleTypeExpr nd, Void c) {
for (ITypeExpression type : nd.getElementTypes()) {
type.accept(this, null);
}
return null;
}
@Override
public Void visit(UnionTypeExpr nd, Void c) {
for (ITypeExpression type : nd.getElementTypes()) {
type.accept(this, null);
}
return null;
}
},
null);
return result;
}
}
| 22,816 | 31.972543 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/OffsetTranslation.java | package com.semmle.js.extractor;
import com.semmle.util.data.IntList;
/**
* A mapping of some source range into a set of intervals in an output source range.
*
* <p>The mapping is constructed by adding "anchors": input/output pairs that correspond to the
* beginning of an interval, which is assumed to end at the next anchor.
*/
public class OffsetTranslation {
private IntList anchors = IntList.create();
private IntList deltas = IntList.create();
/** Returns the mapping of x. */
public int get(int x) {
int index = anchors.binarySearch(x);
if (index < 0) {
// The insertion point is -index - 1.
// Get the index immediately before that.
index = -index - 2;
if (index < 0) {
// If queried before the first anchor, use the first anchor anyway.
index = 0;
}
}
return x + deltas.get(index);
}
/**
* Maps the given input offset to the given output offset.
*
* <p>This is added as an anchor. Any offset is mapped based on its closest preceding anchor.
*/
public void set(int from, int to) {
anchors.add(from);
deltas.add(to - from);
}
}
| 1,142 | 27.575 | 95 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/LoCInfo.java | package com.semmle.js.extractor;
/**
* Utility class for representing LoC information; really just a glorified <code>
* Pair<Integer, Integer></code>.
*/
public class LoCInfo {
private int linesOfCode, linesOfComments;
public LoCInfo(int linesOfCode, int linesOfComments) {
this.linesOfCode = linesOfCode;
this.linesOfComments = linesOfComments;
}
public void add(LoCInfo that) {
this.linesOfCode += that.linesOfCode;
this.linesOfComments += that.linesOfComments;
}
public int getLinesOfCode() {
return linesOfCode;
}
public int getLinesOfComments() {
return linesOfComments;
}
}
| 636 | 21.75 | 81 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/TypeExprKinds.java | package com.semmle.js.extractor;
import com.semmle.jcorn.TokenType;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.extractor.ASTExtractor.IdContext;
import com.semmle.ts.ast.ArrayTypeExpr;
import com.semmle.ts.ast.ConditionalTypeExpr;
import com.semmle.ts.ast.FunctionTypeExpr;
import com.semmle.ts.ast.GenericTypeExpr;
import com.semmle.ts.ast.ImportTypeExpr;
import com.semmle.ts.ast.IndexedAccessTypeExpr;
import com.semmle.ts.ast.InferTypeExpr;
import com.semmle.ts.ast.InterfaceTypeExpr;
import com.semmle.ts.ast.IntersectionTypeExpr;
import com.semmle.ts.ast.KeywordTypeExpr;
import com.semmle.ts.ast.MappedTypeExpr;
import com.semmle.ts.ast.OptionalTypeExpr;
import com.semmle.ts.ast.ParenthesizedTypeExpr;
import com.semmle.ts.ast.PredicateTypeExpr;
import com.semmle.ts.ast.RestTypeExpr;
import com.semmle.ts.ast.TupleTypeExpr;
import com.semmle.ts.ast.TypeParameter;
import com.semmle.ts.ast.TypeofTypeExpr;
import com.semmle.ts.ast.UnaryTypeExpr;
import com.semmle.ts.ast.UnionTypeExpr;
import com.semmle.util.exception.CatastrophicError;
public class TypeExprKinds {
private static final int simpleTypeAccess = 0;
private static final int typeDecl = 1;
private static final int keywordTypeExpr = 2;
private static final int stringLiteralTypeExpr = 3;
private static final int numberLiteralTypeExpr = 4;
private static final int booeleanLiteralTypeExpr = 5;
private static final int arrayTypeExpr = 6;
private static final int unionTypeExpr = 7;
private static final int indexedAccessTypeExpr = 8;
private static final int intersectionTypeExpr = 9;
private static final int parenthesizedTypeExpr = 10;
private static final int tupleTypeExpr = 11;
private static final int keyofTypeExpr = 12;
private static final int qualifiedTypeAccess = 13;
private static final int genericTypeExpr = 14;
private static final int typeLabel = 15;
private static final int typeofTypeExpr = 16;
private static final int simpleVarTypeAccess = 17;
private static final int qualifiedVarTypeAccess = 18;
private static final int thisVarTypeAccess = 19;
private static final int isTypeExpr = 20;
private static final int interfaceTypeExpr = 21;
private static final int typeParameter = 22;
private static final int plainFunctionTypeExpr = 23;
private static final int constructorTypeExpr = 24;
private static final int simpleNamespaceAccess = 25;
private static final int qualifiedNamespaceAccess = 26;
private static final int mappedTypeExpr = 27;
private static final int conditionalTypeExpr = 28;
private static final int inferTypeExpr = 29;
private static final int importTypeAccess = 30;
private static final int importNamespaceAccess = 31;
private static final int importVarTypeAccess = 32;
private static final int optionalTypeExpr = 33;
private static final int restTypeExpr = 34;
private static final int bigintLiteralTypeExpr = 35;
private static final int readonlyTypeExpr = 36;
public static int getTypeExprKind(final INode type, final IdContext idcontext) {
Integer kind =
type.accept(
new DefaultVisitor<Void, Integer>() {
@Override
public Integer visit(Identifier nd, Void c) {
switch (idcontext) {
case typeDecl:
return TypeExprKinds.typeDecl;
case typeBind:
return simpleTypeAccess;
case varInTypeBind:
return simpleVarTypeAccess;
case namespaceBind:
return simpleNamespaceAccess;
default:
return typeLabel;
}
}
@Override
public Integer visit(KeywordTypeExpr nd, Void c) {
if (idcontext == IdContext.varInTypeBind && nd.getKeyword().equals("this")) {
return thisVarTypeAccess;
}
return keywordTypeExpr;
}
@Override
public Integer visit(ArrayTypeExpr nd, Void c) {
return arrayTypeExpr;
}
@Override
public Integer visit(UnionTypeExpr nd, Void c) {
return unionTypeExpr;
}
@Override
public Integer visit(IndexedAccessTypeExpr nd, Void c) {
return indexedAccessTypeExpr;
}
@Override
public Integer visit(IntersectionTypeExpr nd, Void c) {
return intersectionTypeExpr;
}
@Override
public Integer visit(ParenthesizedTypeExpr nd, Void c) {
return parenthesizedTypeExpr;
}
@Override
public Integer visit(TupleTypeExpr nd, Void c) {
return tupleTypeExpr;
}
@Override
public Integer visit(UnaryTypeExpr nd, Void c) {
switch (nd.getKind()) {
case Keyof:
return keyofTypeExpr;
case Readonly:
return readonlyTypeExpr;
}
throw new CatastrophicError("Unhandled UnaryTypeExpr kind: " + nd.getKind());
}
@Override
public Integer visit(MemberExpression nd, Void c) {
if (idcontext == IdContext.varInTypeBind) {
return qualifiedVarTypeAccess;
} else if (idcontext == IdContext.namespaceBind) {
return qualifiedNamespaceAccess;
} else {
return qualifiedTypeAccess;
}
}
@Override
public Integer visit(GenericTypeExpr nd, Void c) {
return genericTypeExpr;
}
@Override
public Integer visit(TypeofTypeExpr nd, Void c) {
return typeofTypeExpr;
}
@Override
public Integer visit(PredicateTypeExpr nd, Void c) {
return isTypeExpr;
}
@Override
public Integer visit(InterfaceTypeExpr nd, Void c) {
return interfaceTypeExpr;
}
@Override
public Integer visit(Literal nd, Void c) {
TokenType type = nd.getTokenType();
if (nd.getValue() == null) {
// We represent the null type as a keyword type in QL, but in the extractor AST
// it is a Literal because the TypeScript AST does not distinguish those.
//
// Main reasons not to expose the null type as a literal type:
// - TypeScript documentation does not treat the null type as a literal type.
// - There is an "undefined" type, but there is no "undefined" literal.
return keywordTypeExpr;
} else if (type == TokenType.string) {
return stringLiteralTypeExpr;
} else if (type == TokenType.num) {
return numberLiteralTypeExpr;
} else if (type == TokenType._true || type == TokenType._false) {
return booeleanLiteralTypeExpr;
} else if (type == TokenType.bigint) {
return bigintLiteralTypeExpr;
} else {
throw new CatastrophicError(
"Unsupported literal type expression kind: " + nd.getValue().getClass());
}
}
@Override
public Integer visit(TypeParameter nd, Void c) {
return typeParameter;
}
@Override
public Integer visit(FunctionTypeExpr nd, Void c) {
return nd.isConstructor() ? constructorTypeExpr : plainFunctionTypeExpr;
}
@Override
public Integer visit(MappedTypeExpr nd, Void c) {
return mappedTypeExpr;
}
@Override
public Integer visit(ConditionalTypeExpr nd, Void c) {
return conditionalTypeExpr;
}
@Override
public Integer visit(InferTypeExpr nd, Void c) {
return inferTypeExpr;
}
@Override
public Integer visit(ImportTypeExpr nd, Void c) {
switch (idcontext) {
case namespaceBind:
return importNamespaceAccess;
case typeBind:
return importTypeAccess;
case varInTypeBind:
return importVarTypeAccess;
default:
return importTypeAccess;
}
}
@Override
public Integer visit(OptionalTypeExpr nd, Void c) {
return optionalTypeExpr;
}
@Override
public Integer visit(RestTypeExpr nd, Void c) {
return restTypeExpr;
}
},
null);
if (kind == null)
throw new CatastrophicError("Unsupported type expression kind: " + type.getClass());
return kind;
}
}
| 9,516 | 36.916335 | 97 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/EnvironmentVariables.java | package com.semmle.js.extractor;
import com.semmle.util.exception.UserError;
import com.semmle.util.process.Env;
import com.semmle.util.process.Env.Var;
public class EnvironmentVariables {
public static final String CODEQL_EXTRACTOR_JAVASCRIPT_ROOT_ENV_VAR =
"CODEQL_EXTRACTOR_JAVASCRIPT_ROOT";
public static final String CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR =
"CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR";
public static final String LGTM_WORKSPACE_ENV_VAR =
"LGTM_WORKSPACE";
/**
* Gets the extractor root based on the <code>CODEQL_EXTRACTOR_JAVASCRIPT_ROOT</code> or <code>
* SEMMLE_DIST</code> or environment variable, or <code>null</code> if neither is set.
*/
public static String tryGetExtractorRoot() {
String env = Env.systemEnv().getNonEmpty(CODEQL_EXTRACTOR_JAVASCRIPT_ROOT_ENV_VAR);
if (env != null) return env;
env = Env.systemEnv().getNonEmpty(Var.SEMMLE_DIST);
if (env != null) return env;
return null;
}
/**
* Gets the extractor root based on the <code>CODEQL_EXTRACTOR_JAVASCRIPT_ROOT</code> or <code>
* SEMMLE_DIST</code> or environment variable, or throws a UserError if neither is set.
*/
public static String getExtractorRoot() {
String env = tryGetExtractorRoot();
if (env == null) {
throw new UserError("SEMMLE_DIST or CODEQL_EXTRACTOR_JAVASCRIPT_ROOT must be set");
}
return env;
}
/**
* Gets the scratch directory from the appropriate environment variable.
*/
public static String getScratchDir() {
String env = Env.systemEnv().getNonEmpty(CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR);
if (env != null) return env;
env = Env.systemEnv().getNonEmpty(LGTM_WORKSPACE_ENV_VAR);
if (env != null) return env;
throw new UserError(CODEQL_EXTRACTOR_JAVASCRIPT_SCRATCH_DIR_ENV_VAR + " or " + LGTM_WORKSPACE_ENV_VAR + " must be set");
}
}
| 1,901 | 34.886792 | 124 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/DependencyInstallationResult.java | package com.semmle.js.extractor;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
/** Contains the results of installing dependencies. */
public class DependencyInstallationResult {
private Map<String, Path> packageEntryPoints;
private Map<String, Path> packageJsonFiles;
public static final DependencyInstallationResult empty =
new DependencyInstallationResult(Collections.emptyMap(), Collections.emptyMap());
public DependencyInstallationResult(
Map<String, Path> packageEntryPoints,
Map<String, Path> packageJsonFiles) {
this.packageEntryPoints = packageEntryPoints;
this.packageJsonFiles = packageJsonFiles;
}
/**
* Returns the mapping from package names to the TypeScript file that should
* act as its main entry point.
*/
public Map<String, Path> getPackageEntryPoints() {
return packageEntryPoints;
}
/**
* Returns the mapping from package name to corresponding package.json.
*/
public Map<String, Path> getPackageJsonFiles() {
return packageJsonFiles;
}
}
| 1,071 | 27.972973 | 87 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/JSONExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.json.JSONArray;
import com.semmle.js.ast.json.JSONLiteral;
import com.semmle.js.ast.json.JSONObject;
import com.semmle.js.ast.json.JSONValue;
import com.semmle.js.ast.json.Visitor;
import com.semmle.js.parser.JSONParser;
import com.semmle.js.parser.ParseError;
import com.semmle.util.data.Pair;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.List;
/** Extractor for populating JSON files. */
public class JSONExtractor implements IExtractor {
private static class Context {
private final Label parent;
private final int childIndex;
public Context(Label parent, int childIndex) {
this.parent = parent;
this.childIndex = childIndex;
}
}
private final boolean tolerateParseErrors;
public JSONExtractor(ExtractorConfig config) {
this.tolerateParseErrors = config.isTolerateParseErrors();
}
@Override
public LoCInfo extract(final TextualExtractor textualExtractor) {
final TrapWriter trapwriter = textualExtractor.getTrapwriter();
final LocationManager locationManager = textualExtractor.getLocationManager();
try {
String source = textualExtractor.getSource();
Pair<JSONValue, List<ParseError>> res = new JSONParser().parseValue(source);
JSONValue v = res.fst();
List<ParseError> recoverableErrors = res.snd();
if (!recoverableErrors.isEmpty() && !tolerateParseErrors)
throw recoverableErrors.get(0).asUserError();
Label fileLabel = locationManager.getFileLabel();
locationManager.setHasLocationTable("json_locations");
v.accept(
new Visitor<Context, Label>() {
private Label emit(JSONValue nd, int kind, Context c) {
Label label = trapwriter.localID(nd);
trapwriter.addTuple(
"json", label, kind, c.parent, c.childIndex, textualExtractor.mkToString(nd));
locationManager.emitNodeLocation(nd, label);
return label;
}
@Override
public Label visit(JSONLiteral nd, Context c) {
int kind = 0;
if (nd.getValue() instanceof Boolean) kind = 1;
else if (nd.getValue() instanceof Number) kind = 2;
else if (nd.getValue() instanceof String) kind = 3;
Label label = emit(nd, kind, c);
trapwriter.addTuple("json_literals", nd.getStringValue(), nd.getRaw(), label);
return label;
}
@Override
public Label visit(JSONArray nd, Context c) {
Label label = emit(nd, 4, c);
int i = 0;
for (JSONValue element : nd.getElements())
element.accept(this, new Context(label, i++));
return label;
}
@Override
public Label visit(JSONObject nd, Context c) {
Label label = emit(nd, 5, c);
int i = 0;
for (Pair<String, JSONValue> prop : nd.getProperties()) {
String name = prop.fst();
Label vallabel = prop.snd().accept(this, new Context(label, i++));
trapwriter.addTuple("json_properties", label, name, vallabel);
}
return label;
}
},
new Context(fileLabel, 0));
for (ParseError e : recoverableErrors)
populateError(textualExtractor, trapwriter, locationManager, e);
} catch (ParseError e) {
if (!this.tolerateParseErrors) throw e.asUserError();
populateError(textualExtractor, trapwriter, locationManager, e);
}
return new LoCInfo(0, 0);
}
private void populateError(
final TextualExtractor textualExtractor,
final TrapWriter trapwriter,
final LocationManager locationManager,
ParseError e) {
Label label = trapwriter.freshLabel();
trapwriter.addTuple("json_errors", label, "Error: " + e);
locationManager.emitErrorLocation(label, e.getPosition(), textualExtractor.getNumLines());
}
}
| 4,098 | 35.598214 | 96 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/TypeScriptMode.java | package com.semmle.js.extractor;
/** The amount of information to extract from TypeScript files. */
public enum TypeScriptMode {
/** TypeScript files will not be extracted. */
NONE,
/**
* Only syntactic information will be extracted from TypeScript files.
*
* <p>This requires Node.js and the TypeScript compiler to be installed if the project contains
* any TypeScript files.
*/
BASIC,
/** Extract as much as possible from TypeScript files. */
FULL;
}
| 483 | 24.473684 | 97 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/TextualExtractor.java | package com.semmle.js.extractor;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.SourceElement;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
/**
* Extractor for populating purely textual information about a file, namely its lines and their line
* terminators.
*/
public class TextualExtractor {
private static final Pattern LINE_TERMINATOR = Pattern.compile("\\n|\\r\\n|\\r|\\u2028|\\u2029");
private static final Pattern INDENT_CHAR = Pattern.compile("((\\s)\\2*)\\S.*");
private final String source;
private final TrapWriter trapwriter;
private final LocationManager locationManager;
private final Label fileLabel;
private final boolean extractLines;
private final ExtractionMetrics metrics;
private final File extractedFile;
public TextualExtractor(
TrapWriter trapwriter,
LocationManager locationManager,
String source,
boolean extractLines,
ExtractionMetrics metrics,
File extractedFile) {
this.trapwriter = trapwriter;
this.locationManager = locationManager;
this.source = source;
this.fileLabel = locationManager.getFileLabel();
this.extractLines = extractLines;
this.metrics = metrics;
this.extractedFile = extractedFile;
}
/**
* Returns the file whose contents should be extracted, and is contained
* in {@link #source}.
*
* <p>This may differ from the source file of the location manager, which refers
* to the original file that this was derived from.
*/
public File getExtractedFile() {
return extractedFile;
}
/**
* Returns true if the extracted file and the source location files are different.
*/
public boolean isSnippet() {
return !extractedFile.equals(locationManager.getSourceFile());
}
public TrapWriter getTrapwriter() {
return trapwriter;
}
public LocationManager getLocationManager() {
return locationManager;
}
public String getSource() {
return source;
}
public ExtractionMetrics getMetrics() {
return metrics;
}
public String mkToString(SourceElement nd) {
return sanitiseToString(nd.getLoc().getSource());
}
private static final String esc = "\nn\rr\tt";
public static String sanitiseToString(String str) {
if (str.length() > 20) str = str.substring(0, 7) + " ... " + str.substring(str.length() - 7);
StringBuilder res = new StringBuilder();
for (int i = 0, n = str.length(); i < n; ++i) {
int c = str.codePointAt(i);
if (c < 0x20 || c > 0x7e) {
int j = esc.indexOf(c);
if (j >= 0) res.append("\\" + esc.charAt(j + 1));
else res.append("\\u" + String.format("%04x", Integer.valueOf(c)));
} else {
res.append((char) c);
}
}
return res.toString();
}
/**
* Emit a lines/4 tuple, if {@link #extractLines} is {@code true}, and an indentation/4 tuple,
* where applicable, for a line of source code.
*
* @param line the text of the line
* @param term the line terminator
* @param i the line number
*/
public void extractLine(String line, String term, int i, Label toplevelKey) {
if (extractLines) {
Label key = trapwriter.freshLabel();
trapwriter.addTuple("lines", key, toplevelKey, line, term);
locationManager.emitSnippetLocation(key, i, 1, i, line.length());
}
Matcher indentCharMatcher = INDENT_CHAR.matcher(line);
if (indentCharMatcher.matches()) {
// translate logical line number `i` into actual line number within file
int lineno = locationManager.translatePosition(new Position(i, 1, 0)).getLine();
String indentChar = indentCharMatcher.group(2);
int indentDepth = indentCharMatcher.group(1).length();
trapwriter.addTuple("indentation", fileLabel, lineno, indentChar, indentDepth);
}
}
/** Extract lexical information about source lines and line numbers. */
public Position extractLines(String src, Label toplevelKey) {
int len = src.length(), i = 1, start = 0, llength = 0;
Matcher matcher = LINE_TERMINATOR.matcher(src);
while (matcher.find()) {
String line = src.substring(start, matcher.start());
llength = line.length();
extractLine(line, matcher.group(), i++, toplevelKey);
start = matcher.end();
}
if (start < len) {
extractLine(src.substring(start), "", i, toplevelKey);
llength = len - start;
} else {
--i;
}
return new Position(i, llength, len);
}
public int getNumLines() {
Matcher matcher = LINE_TERMINATOR.matcher(source);
int n = 0, end = 0;
while (matcher.find()) {
++n;
end = matcher.end();
}
if (end < source.length()) ++n;
return n;
}
public String getLine(int lineNumber) {
Matcher matcher = LINE_TERMINATOR.matcher(source);
int n = 1, end = 0;
while (matcher.find()) {
if (n == lineNumber) return source.substring(end, matcher.end());
++n;
end = matcher.end();
}
return source.substring(end);
}
}
| 5,119 | 29.117647 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/AutoBuild.java | package com.semmle.js.extractor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.ProcessBuilder.Redirect;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.extractor.FileExtractor.FileType;
import com.semmle.js.extractor.trapcache.DefaultTrapCache;
import com.semmle.js.extractor.trapcache.DummyTrapCache;
import com.semmle.js.extractor.trapcache.ITrapCache;
import com.semmle.js.parser.ParsedProject;
import com.semmle.js.parser.TypeScriptParser;
import com.semmle.ts.extractor.TypeExtractor;
import com.semmle.ts.extractor.TypeTable;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.CatastrophicError;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.exception.ResourceError;
import com.semmle.util.exception.UserError;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.files.FileUtil;
import com.semmle.util.io.WholeIO;
import com.semmle.util.io.csv.CSVReader;
import com.semmle.util.language.LegacyLanguage;
import com.semmle.util.process.Env;
import com.semmle.util.projectstructure.ProjectLayout;
import com.semmle.util.trap.TrapWriter;
/**
* An alternative entry point to the JavaScript extractor.
*
* <p>It assumes the following environment variables to be set:
*
* <ul>
* <li><code>LGTM_SRC</code>: the source root;
* <li><code>SEMMLE_DIST</code>: the distribution root.
* </ul>
*
* <p>Additionally, the following environment variables may be set to customise extraction
* (explained in more detail below):
*
* <ul>
* <li><code>LGTM_INDEX_INCLUDE</code>: a newline-separated list of paths to include
* <li><code>LGTM_INDEX_EXCLUDE</code>: a newline-separated list of paths to exclude
* <li><code>LGTM_REPOSITORY_FOLDERS_CSV</code>: the path of a CSV file containing file
* classifications
* <li><code>LGTM_INDEX_FILTERS</code>: a newline-separated list of strings of form "include:PATTERN"
* or "exclude:PATTERN" that can be used to refine the list of files to include and exclude.
* <li><code>LGTM_INDEX_TYPESCRIPT</code>: whether to extract TypeScript
* <li><code>LGTM_INDEX_FILETYPES</code>: a newline-separated list of ".extension:filetype" pairs
* specifying which {@link FileType} to use for the given extension; the additional file type
* <code>XML</code> is also supported
* <li><code>LGTM_INDEX_XML_MODE</code>: whether to extract XML files
* <li><code>LGTM_THREADS</code>: the maximum number of files to extract in parallel
* <li><code>LGTM_TRAP_CACHE</code>: the path of a directory to use for trap caching
* <li><code>LGTM_TRAP_CACHE_BOUND</code>: the size to bound the trap cache to
* </ul>
*
* <p>It extracts the following:
*
* <ol>
* <li>all <code>*.js</code> files under <code>$SEMMLE_DIST/tools/data/externs</code> (cf. {@link
* AutoBuild#extractExterns()};
* <li>all source code files (cf. {@link AutoBuild#extractSource()}.
* </ol>
*
* <p>In the second step, the set of files to extract is determined in two phases: the walking
* phase, which computes a set of candidate files, and the filtering phase. A file is extracted if
* it is a candidate, its type is supported (cf. {@link FileExtractor#supports(File)}), and it is
* not filtered out in the filtering phase.
*
* <p>The walking phase is parameterised by a set of <i>include paths</i> and a set of <i>exclude
* paths</i>. By default, the single include path is <code>LGTM_SRC</code>. If the environment
* variable <code>LGTM_INDEX_INCLUDE</code> is set, it is interpreted as a newline-separated list of
* include paths, which are slash-separated paths relative to <code>LGTM_SRC</code>. This list
* <i>replaces</i> (rather than extends) the default include path.
*
* <p>Similarly, the set of exclude paths is determined by the environment variables <code>
* LGTM_INDEX_EXCLUDE</code> and <code>LGTM_REPOSITORY_FOLDERS_CSV</code>. The former is interpreted
* like <code>LGTM_INDEX_EXCLUDE</code>, that is, a newline-separated list of exclude paths relative
* to <code>LGTM_SRC</code>. The latter is interpreted as the path of a CSV file, where each line in
* the file consists of a classification tag and an absolute path; any path classified as "external"
* or "metadata" becomes an exclude path. Note that there are no implicit exclude paths.
*
* <p>The walking phase starts at each include path in turn and recursively traverses folders and
* files. Symlinks and hidden folders are skipped, but not hidden files. If it encounters a
* sub-folder whose path is excluded, traversal stops. If it encounters a file, that file becomes a
* candidate, unless its path is excluded. If the path of a file is both an include path and an
* exclude path, the inclusion takes precedence, and the file becomes a candidate after all.
*
* <p>If an include or exclude path cannot be resolved, a warning is printed and the path is
* ignored.
*
* <p>Note that the overall effect of this procedure is that the precedence of include and exclude
* paths is derived from their specificity: a more specific include/exclude takes precedence over a
* less specific include/exclude. In case of a tie, the include takes precedence.
*
* <p>The filtering phase is parameterised by a list of include/exclude patterns in the style of
* {@link ProjectLayout} specifications. There are some built-in include/exclude patterns discussed
* below. Additionally, the environment variable <code>LGTM_INDEX_FILTERS</code> is interpreted as a
* newline-separated list of patterns to append to that list (hence taking precedence over the
* built-in patterns). Unlike for {@link ProjectLayout}, patterns in <code>LGTM_INDEX_FILTERS</code>
* use the syntax <code>include: pattern</code> for inclusions and <code>exclude: pattern</code> for
* exclusions.
*
* <p>The default inclusion patterns cause the following files to be included:
*
* <ul>
* <li>All JavaScript files, that is, files with one of the extensions supported by {@link
* FileType#JS} (currently ".js", ".jsx", ".mjs", ".es6", ".es").
* <li>All HTML files, that is, files with with one of the extensions supported by {@link
* FileType#HTML} (currently ".htm", ".html", ".xhtm", ".xhtml", ".vue").
* <li>All YAML files, that is, files with one of the extensions supported by {@link
* FileType#YAML} (currently ".raml", ".yaml", ".yml").
* <li>Files with base name "package.json".
* <li>JavaScript, JSON or YAML files whose base name starts with ".eslintrc".
* <li>All extension-less files.
* </ul>
*
* <p>Additionally, if the environment variable <code>LGTM_INDEX_TYPESCRIPT</code> is set to "basic"
* or "full" (default), files with one of the extensions supported by {@link FileType#TYPESCRIPT}
* (currently ".ts" and ".tsx") are also included. In case of "full", type information from the
* TypeScript compiler is extracted as well.
*
* <p>The environment variable <code>LGTM_INDEX_FILETYPES</code> may be set to a newline-separated
* list of file type specifications of the form <code>.extension:filetype</code>, causing all files
* whose name ends in <code>.extension</code> to also be included by default.
*
* <p>The default exclusion patterns cause the following files to be excluded:
*
* <ul>
* <li>All JavaScript files whose name ends with <code>-min.js</code> or <code>.min.js</code>.
* Such files typically contain minified code. Since LGTM by default does not show results in
* minified files, it is not usually worth extracting them in the first place.
* </ul>
*
* <p>JavaScript files are normally extracted with {@link SourceType#AUTO}, but an explicit source
* type can be specified in the environment variable <code>LGTM_INDEX_SOURCE_TYPE</code>.
*
* <p>The file type as which a file is extracted can be customised via the <code>
* LGTM_INDEX_FILETYPES</code> environment variable explained above.
*
* <p>If <code>LGTM_INDEX_XML_MODE</code> is set to <code>ALL</code>, then all files with extension
* <code>.xml</code> under <code>LGTM_SRC</code> are extracted as XML (in addition to any files
* whose file type is specified to be <code>XML</code> via <code>LGTM_INDEX_SOURCE_TYPE</code>).
* Currently XML extraction does not respect inclusion and exclusion filters, but this is a bug, not
* a feature, and hence will change eventually.
*
* <p>Note that all these customisations only apply to <code>LGTM_SRC</code>. Extraction of externs
* is not customisable.
*
* <p>To customise the actual extraction (as opposed to determining which files to extract), the
* following environment variables are available:
*
* <ul>
* <li><code>LGTM_THREADS</code> determines how many threads are used for parallel extraction of
* JavaScript files (TypeScript files cannot currently be extracted in parallel). If left
* unspecified, the extractor uses a single thread.
* <li><code>LGTM_TRAP_CACHE</code> and <code>LGTM_TRAP_CACHE_BOUND</code> can be used to specify
* the location and size of a trap cache to be used during extraction.
* </ul>
*/
public class AutoBuild {
private final ExtractorOutputConfig outputConfig;
private final ITrapCache trapCache;
private final Map<String, FileType> fileTypes = new LinkedHashMap<>();
private final Set<Path> includes = new LinkedHashSet<>();
private final Set<Path> excludes = new LinkedHashSet<>();
private final Set<String> xmlExtensions = new LinkedHashSet<>();
private ProjectLayout filters;
private final Path LGTM_SRC, SEMMLE_DIST;
private final TypeScriptMode typeScriptMode;
private final String defaultEncoding;
private ExecutorService threadPool;
private volatile boolean seenCode = false;
private volatile boolean seenFiles = false;
private boolean installDependencies = false;
private int installDependenciesTimeout;
private final VirtualSourceRoot virtualSourceRoot;
private ExtractorState state;
/** The default timeout when running <code>yarn</code>, in milliseconds. */
public static final int INSTALL_DEPENDENCIES_DEFAULT_TIMEOUT = 10 * 60 * 1000; // 10 minutes
public AutoBuild() {
this.LGTM_SRC = toRealPath(getPathFromEnvVar("LGTM_SRC"));
this.SEMMLE_DIST = Paths.get(EnvironmentVariables.getExtractorRoot());
this.outputConfig = new ExtractorOutputConfig(LegacyLanguage.JAVASCRIPT);
this.trapCache = mkTrapCache();
this.typeScriptMode =
getEnumFromEnvVar("LGTM_INDEX_TYPESCRIPT", TypeScriptMode.class, TypeScriptMode.FULL);
this.defaultEncoding = getEnvVar("LGTM_INDEX_DEFAULT_ENCODING");
this.installDependencies = Boolean.valueOf(getEnvVar("LGTM_INDEX_TYPESCRIPT_INSTALL_DEPS"));
this.installDependenciesTimeout =
Env.systemEnv()
.getInt(
"LGTM_INDEX_TYPESCRIPT_INSTALL_DEPS_TIMEOUT", INSTALL_DEPENDENCIES_DEFAULT_TIMEOUT);
this.virtualSourceRoot = makeVirtualSourceRoot();
setupFileTypes();
setupXmlMode();
setupMatchers();
this.state = new ExtractorState();
}
protected VirtualSourceRoot makeVirtualSourceRoot() {
return new VirtualSourceRoot(LGTM_SRC, toRealPath(Paths.get(EnvironmentVariables.getScratchDir())));
}
private String getEnvVar(String envVarName) {
return getEnvVar(envVarName, null);
}
private String getEnvVar(String envVarName, String deflt) {
String value = Env.systemEnv().getNonEmpty(envVarName);
if (value == null) return deflt;
return value;
}
private Path getPathFromEnvVar(String envVarName) {
String lgtmSrc = getEnvVar(envVarName);
if (lgtmSrc == null) throw new UserError(envVarName + " must be set.");
Path path = Paths.get(lgtmSrc);
return path;
}
private <T extends Enum<T>> T getEnumFromEnvVar(
String envVarName, Class<T> enumClass, T defaultValue) {
String envValue = getEnvVar(envVarName);
if (envValue == null) return defaultValue;
try {
return Enum.valueOf(enumClass, StringUtil.uc(envValue));
} catch (IllegalArgumentException ex) {
Exceptions.ignore(ex, "We rewrite this to a meaningful user error.");
Stream<String> enumNames =
Arrays.asList(enumClass.getEnumConstants()).stream()
.map(c -> StringUtil.lc(c.toString()));
throw new UserError(
envVarName + " must be set to one of: " + StringUtil.glue(", ", enumNames.toArray()));
}
}
/**
* Convert {@code p} to a real path (as per {@link Path#toRealPath(java.nio.file.LinkOption...)}),
* throwing a {@link ResourceError} if this fails.
*/
private Path toRealPath(Path p) {
try {
return p.toRealPath();
} catch (IOException e) {
throw new ResourceError("Could not compute real path for " + p + ".", e);
}
}
/**
* Set up TRAP cache based on environment variables <code>LGTM_TRAP_CACHE</code> and <code>
* LGTM_TRAP_CACHE_BOUND</code>.
*/
private ITrapCache mkTrapCache() {
ITrapCache trapCache;
String trapCachePath = getEnvVar("LGTM_TRAP_CACHE");
if (trapCachePath != null) {
Long sizeBound = null;
String trapCacheBound = getEnvVar("LGTM_TRAP_CACHE_BOUND");
if (trapCacheBound != null) {
sizeBound = DefaultTrapCache.asFileSize(trapCacheBound);
if (sizeBound == null)
throw new UserError("Invalid TRAP cache size bound: " + trapCacheBound);
}
trapCache = new DefaultTrapCache(trapCachePath, sizeBound, Main.EXTRACTOR_VERSION);
} else {
trapCache = new DummyTrapCache();
}
return trapCache;
}
private void setupFileTypes() {
for (String spec : Main.NEWLINE.split(getEnvVar("LGTM_INDEX_FILETYPES", ""))) {
spec = spec.trim();
if (spec.isEmpty()) continue;
String[] fields = spec.split(":");
if (fields.length != 2) continue;
String extension = fields[0].trim();
String fileType = fields[1].trim();
try {
fileType = StringUtil.uc(fileType);
if ("XML".equals(fileType)) {
if (extension.length() < 2) throw new UserError("Invalid extension '" + extension + "'.");
xmlExtensions.add(extension.substring(1));
} else {
fileTypes.put(extension, FileType.valueOf(fileType));
}
} catch (IllegalArgumentException e) {
Exceptions.ignore(e, "We construct a better error message.");
throw new UserError("Invalid file type '" + fileType + "'.");
}
}
}
private void setupXmlMode() {
String xmlMode = getEnvVar("LGTM_INDEX_XML_MODE", "DISABLED");
xmlMode = StringUtil.uc(xmlMode.trim());
if ("ALL".equals(xmlMode)) xmlExtensions.add("xml");
else if (!"DISABLED".equals(xmlMode))
throw new UserError("Invalid XML mode '" + xmlMode + "' (should be either ALL or DISABLED).");
}
/** Set up include and exclude matchers based on environment variables. */
private void setupMatchers() {
setupIncludesAndExcludes();
setupFilters();
}
/**
* Set up include matchers based on <code>LGTM_INDEX_INCLUDE</code> and <code>
* LGTM_INDEX_TYPESCRIPT</code>.
*/
private void setupIncludesAndExcludes() {
// process `$LGTM_INDEX_INCLUDE` and `$LGTM_INDEX_EXCLUDE`
boolean seenInclude = false;
for (String pattern : Main.NEWLINE.split(getEnvVar("LGTM_INDEX_INCLUDE", "")))
seenInclude |= addPathPattern(includes, LGTM_SRC, pattern);
if (!seenInclude) includes.add(LGTM_SRC);
for (String pattern : Main.NEWLINE.split(getEnvVar("LGTM_INDEX_EXCLUDE", "")))
addPathPattern(excludes, LGTM_SRC, pattern);
// process `$LGTM_REPOSITORY_FOLDERS_CSV`
String lgtmRepositoryFoldersCsv = getEnvVar("LGTM_REPOSITORY_FOLDERS_CSV");
if (lgtmRepositoryFoldersCsv != null) {
Path path = Paths.get(lgtmRepositoryFoldersCsv);
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
CSVReader csv = new CSVReader(reader)) {
// skip titles
csv.readNext();
String[] fields;
while ((fields = csv.readNext()) != null) {
if (fields.length != 2) continue;
if ("external".equals(fields[0]) || "metadata".equals(fields[0])) {
String folder = fields[1];
try {
Path folderPath =
folder.startsWith("file://") ? Paths.get(new URI(folder)) : Paths.get(folder);
excludes.add(toRealPath(folderPath));
} catch (InvalidPathException | URISyntaxException | ResourceError e) {
Exceptions.ignore(e, "Ignore path and print warning message instead");
warn(
"Ignoring '"
+ fields[0]
+ "' classification for "
+ folder
+ ", which is not a valid path.");
}
}
}
} catch (IOException e) {
throw new ResourceError("Unable to process LGTM repository folder CSV.", e);
}
}
}
private void setupFilters() {
List<String> patterns = new ArrayList<String>();
patterns.add("/");
// exclude all files with extensions
patterns.add("-**/*.*");
// but include HTML, JavaScript, YAML and (optionally) TypeScript
Set<FileType> defaultExtract = new LinkedHashSet<FileType>();
defaultExtract.add(FileType.HTML);
defaultExtract.add(FileType.JS);
defaultExtract.add(FileType.YAML);
if (typeScriptMode != TypeScriptMode.NONE) defaultExtract.add(FileType.TYPESCRIPT);
for (FileType filetype : defaultExtract)
for (String extension : filetype.getExtensions()) patterns.add("**/*" + extension);
// include .eslintrc files, package.json files, and tsconfig.json files
patterns.add("**/.eslintrc*");
patterns.add("**/package.json");
patterns.add("**/tsconfig.json");
// include any explicitly specified extensions
for (String extension : fileTypes.keySet()) patterns.add("**/*" + extension);
// exclude files whose name strongly suggests they are minified
patterns.add("-**/*.min.js");
patterns.add("-**/*-min.js");
// exclude `node_modules` and `bower_components`
patterns.add("-**/node_modules");
patterns.add("-**/bower_components");
String base = LGTM_SRC.toString().replace('\\', '/');
// process `$LGTM_INDEX_FILTERS`
for (String pattern : Main.NEWLINE.split(getEnvVar("LGTM_INDEX_FILTERS", ""))) {
pattern = pattern.trim();
if (pattern.isEmpty()) continue;
String[] fields = pattern.split(":");
if (fields.length != 2) continue;
pattern = fields[1].trim();
pattern = base + "/" + pattern;
if ("exclude".equals(fields[0].trim())) pattern = "-" + pattern;
patterns.add(pattern);
}
filters = new ProjectLayout(patterns.toArray(new String[0]));
}
/**
* Add {@code pattern} to {@code patterns}, trimming off whitespace and prepending {@code base} to
* it. If {@code pattern} ends with a trailing slash, that slash is stripped off.
*
* @return true if {@code pattern} is non-empty
*/
private boolean addPathPattern(Set<Path> patterns, Path base, String pattern) {
pattern = pattern.trim();
if (pattern.isEmpty()) return false;
Path path = base.resolve(pattern);
try {
Path realPath = toRealPath(path);
patterns.add(realPath);
} catch (ResourceError e) {
Exceptions.ignore(e, "Ignore exception and print warning instead.");
warn("Skipping path " + path + ", which does not exist.");
}
return true;
}
/** Perform extraction. */
public int run() throws IOException {
startThreadPool();
try {
extractSource();
extractExterns();
extractXml();
} finally {
shutdownThreadPool();
}
if (!seenCode) {
if (seenFiles) {
warn("Only found JavaScript or TypeScript files that were empty or contained syntax errors.");
} else {
warn("No JavaScript or TypeScript code found.");
}
return -1;
}
return 0;
}
private void startThreadPool() {
int defaultNumThreads = 1;
int numThreads = Env.systemEnv().getInt("LGTM_THREADS", defaultNumThreads);
if (numThreads > 1) {
System.out.println("Parallel extraction with " + numThreads + " threads.");
threadPool = Executors.newFixedThreadPool(numThreads);
} else {
System.out.println("Single-threaded extraction.");
threadPool = null;
}
}
private void shutdownThreadPool() {
if (threadPool != null) {
threadPool.shutdown();
try {
threadPool.awaitTermination(365, TimeUnit.DAYS);
} catch (InterruptedException e) {
Exceptions.ignore(e, "Awaiting termination is not essential.");
}
}
}
/** Extract all "*.js" files under <code>$SEMMLE_DIST/tools/data/externs</code> as externs. */
private void extractExterns() throws IOException {
ExtractorConfig config = new ExtractorConfig(false).withExterns(true);
// use explicitly specified trap cache, or otherwise $SEMMLE_DIST/.cache/trap-cache/javascript,
// which we pre-populate when building the distribution
ITrapCache trapCache = this.trapCache;
if (trapCache instanceof DummyTrapCache) {
Path trapCachePath =
SEMMLE_DIST.resolve(".cache").resolve("trap-cache").resolve("javascript");
if (Files.isDirectory(trapCachePath)) {
trapCache =
new DefaultTrapCache(trapCachePath.toString(), null, Main.EXTRACTOR_VERSION) {
boolean warnedAboutCacheMiss = false;
@Override
public File lookup(String source, ExtractorConfig config, FileType type) {
File f = super.lookup(source, config, type);
// only return `f` if it exists; this has the effect of making the cache read-only
if (f.exists()) return f;
// warn on first failed lookup
if (!warnedAboutCacheMiss) {
warn("Trap cache lookup for externs failed.");
warnedAboutCacheMiss = true;
}
return null;
}
};
} else {
warn("No externs trap cache found");
}
}
FileExtractor extractor = new FileExtractor(config, outputConfig, trapCache);
FileVisitor<? super Path> visitor =
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (".js".equals(FileUtil.extension(file.toString()))) extract(extractor, file, true);
return super.visitFile(file, attrs);
}
};
Path externs = SEMMLE_DIST.resolve("tools").resolve("data").resolve("externs");
Files.walkFileTree(externs, visitor);
}
/**
* Compares files in the order they should be extracted.
* <p>
* The ordering of tsconfig.json files can affect extraction results. Since we
* extract any given source file at most once, and a source file can be included from
* multiple tsconfig.json files, we sometimes have to choose arbitrarily which tsconfig.json
* to use for a given file (which is based on this ordering).
* <p>
* We sort them to help ensure reproducible extraction. Additionally, deeply nested files are
* preferred over shallow ones to help ensure files are extracted with the most specific
* tsconfig.json file.
*/
public static final Comparator<Path> PATH_ORDERING = new Comparator<Path>() {
public int compare(Path f1, Path f2) {
if (f1.getNameCount() != f2.getNameCount()) {
return f2.getNameCount() - f1.getNameCount();
}
return f1.compareTo(f2);
}
};
/**
* Like {@link #PATH_ORDERING} but for {@link File} objects.
*/
public static final Comparator<File> FILE_ORDERING = new Comparator<File>() {
public int compare(File f1, File f2) {
return PATH_ORDERING.compare(f1.toPath(), f2.toPath());
}
};
public class FileExtractors {
FileExtractor defaultExtractor;
Map<String, FileExtractor> customExtractors = new LinkedHashMap<>();
FileExtractors(FileExtractor defaultExtractor) {
this.defaultExtractor = defaultExtractor;
}
public FileExtractor forFile(Path f) {
return customExtractors.getOrDefault(FileUtil.extension(f), defaultExtractor);
}
public FileType fileType(Path f) {
return forFile(f).getFileType(f.toFile());
}
}
/** Extract all supported candidate files that pass the filters. */
private void extractSource() throws IOException {
// default extractor
FileExtractor defaultExtractor =
new FileExtractor(mkExtractorConfig(), outputConfig, trapCache);
FileExtractors extractors = new FileExtractors(defaultExtractor);
// custom extractor for explicitly specified file types
for (Map.Entry<String, FileType> spec : fileTypes.entrySet()) {
String extension = spec.getKey();
String fileType = spec.getValue().name();
ExtractorConfig extractorConfig = mkExtractorConfig().withFileType(fileType);
extractors.customExtractors.put(extension, new FileExtractor(extractorConfig, outputConfig, trapCache));
}
Set<Path> filesToExtract = new LinkedHashSet<>();
List<Path> tsconfigFiles = new ArrayList<>();
findFilesToExtract(defaultExtractor, filesToExtract, tsconfigFiles);
tsconfigFiles = tsconfigFiles.stream()
.sorted(PATH_ORDERING)
.collect(Collectors.toList());
filesToExtract = filesToExtract.stream()
.sorted(PATH_ORDERING)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
DependencyInstallationResult dependencyInstallationResult = DependencyInstallationResult.empty;
if (!tsconfigFiles.isEmpty()) {
dependencyInstallationResult = this.preparePackagesAndDependencies(filesToExtract);
}
Set<Path> extractedFiles = new LinkedHashSet<>();
// Extract HTML files as they may contain TypeScript
CompletableFuture<?> htmlFuture = extractFiles(
filesToExtract, extractedFiles, extractors,
f -> extractors.fileType(f) == FileType.HTML);
htmlFuture.join(); // Wait for HTML extraction to be finished.
// extract TypeScript projects and files
extractTypeScript(filesToExtract, extractedFiles,
extractors, tsconfigFiles, dependencyInstallationResult);
boolean hasTypeScriptFiles = extractedFiles.size() > 0;
// extract remaining files
extractFiles(
filesToExtract, extractedFiles, extractors,
f -> !(hasTypeScriptFiles && isFileDerivedFromTypeScriptFile(f, extractedFiles)));
}
private CompletableFuture<?> extractFiles(
Set<Path> filesToExtract,
Set<Path> extractedFiles,
FileExtractors extractors,
Predicate<Path> shouldExtract) {
List<CompletableFuture<?>> futures = new ArrayList<>();
for (Path f : filesToExtract) {
if (extractedFiles.contains(f))
continue;
if (!shouldExtract.test(f)) {
continue;
}
extractedFiles.add(f);
futures.add(extract(extractors.forFile(f), f, true));
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
/**
* Returns true if the given path is likely the output of compiling a TypeScript file
* which we have already extracted.
*/
private boolean isFileDerivedFromTypeScriptFile(Path path, Set<Path> extractedFiles) {
String name = path.getFileName().toString();
if (!name.endsWith(".js"))
return false;
String stem = name.substring(0, name.length() - ".js".length());
for (String ext : FileType.TYPESCRIPT.getExtensions()) {
if (extractedFiles.contains(path.getParent().resolve(stem + ext))) {
return true;
}
}
return false;
}
/** Returns true if yarn is installed, otherwise prints a warning and returns false. */
private boolean verifyYarnInstallation() {
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("yarn", "-v"));
try {
Process process = pb.start();
boolean completed = process.waitFor(this.installDependenciesTimeout, TimeUnit.MILLISECONDS);
if (!completed) {
System.err.println("Yarn could not be launched. Timeout during 'yarn -v'.");
return false;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String version = reader.readLine();
System.out.println("Found yarn version: " + version);
return true;
} catch (IOException | InterruptedException ex) {
System.err.println(
"Yarn not found. Please put 'yarn' on the PATH for automatic dependency installation.");
Exceptions.ignore(ex, "Continue without dependency installation");
return false;
}
}
/**
* Returns an existing file named <code>dir/stem.ext</code> where <code>.ext</code> is any
* of the given extensions, or <code>null</code> if no such file exists.
*/
private static Path tryResolveWithExtensions(Path dir, String stem, Iterable<String> extensions) {
for (String ext : extensions) {
Path path = dir.resolve(stem + ext);
if (Files.exists(dir.resolve(path))) {
return path;
}
}
return null;
}
/**
* Returns an existing file named <code>dir/stem.ext</code> where <code>ext</code> is any TypeScript or JavaScript extension,
* or <code>null</code> if no such file exists.
*/
private static Path tryResolveTypeScriptOrJavaScriptFile(Path dir, String stem) {
Path resolved = tryResolveWithExtensions(dir, stem, FileType.TYPESCRIPT.getExtensions());
if (resolved != null) return resolved;
return tryResolveWithExtensions(dir, stem, FileType.JS.getExtensions());
}
/**
* Gets a child of a JSON object as a string, or <code>null</code>.
*/
private String getChildAsString(JsonObject obj, String name) {
JsonElement child = obj.get(name);
if (child instanceof JsonPrimitive && ((JsonPrimitive)child).isString()) {
return child.getAsString();
}
return null;
}
/**
* Gets a relative path from <code>from</code> to <code>to</code> provided
* the latter is contained in the former. Otherwise returns <code>null</code>.
* @return a path or null
*/
public static Path tryRelativize(Path from, Path to) {
Path relative = from.relativize(to);
if (relative.startsWith("..") || relative.isAbsolute()) {
return null;
}
return relative;
}
/**
* Prepares <tt>package.json</tt> files in a virtual source root, and, if enabled,
* installs dependencies for use by the TypeScript type checker.
* <p>
* Some packages must be downloaded while others exist within the same repo ("monorepos")
* but are not in a location where TypeScript would look for it.
* <p>
* Downloaded packages are intalled under <tt>SCRATCH_DIR</tt>, in a mirrored directory hierarchy
* we call the "virtual source root".
* Each <tt>package.json</tt> file is rewritten and copied to the virtual source root,
* where <tt>yarn install</tt> is invoked.
* <p>
* Packages that exists within the repo are stripped from the dependencies
* before installation, so they are not downloaded. Since they are part of the main source tree,
* these packages are not mirrored under the virtual source root.
* Instead, an explicit package location mapping is passed to the TypeScript parser wrapper.
* <p>
* The TypeScript parser wrapper then overrides module resolution so packages can be found
* under the virtual source root and via that package location mapping.
*/
protected DependencyInstallationResult preparePackagesAndDependencies(Set<Path> filesToExtract) {
final Path sourceRoot = LGTM_SRC;
// Read all package.json files and index them by name.
Map<Path, JsonObject> packageJsonFiles = new LinkedHashMap<>();
Map<String, Path> packagesInRepo = new LinkedHashMap<>();
Map<String, Path> packageMainFile = new LinkedHashMap<>();
for (Path file : filesToExtract) {
if (file.getFileName().toString().equals("package.json")) {
try {
String text = new WholeIO().read(file);
JsonElement json = new JsonParser().parse(text);
if (!(json instanceof JsonObject)) continue;
JsonObject jsonObject = (JsonObject) json;
file = file.toAbsolutePath();
if (tryRelativize(sourceRoot, file) == null) {
continue; // Ignore package.json files outside the source root.
}
packageJsonFiles.put(file, jsonObject);
String name = getChildAsString(jsonObject, "name");
if (name != null) {
packagesInRepo.put(name, file);
}
} catch (JsonParseException e) {
System.err.println("Could not parse JSON file: " + file);
System.err.println(e);
// Continue without the malformed package.json file
}
}
}
// Process all package.json files now that we know the names of all local packages.
// - remove dependencies on local packages
// - guess the main file for each package
// Note that we ignore optional dependencies during installation, so "optionalDependencies"
// is ignored here as well.
final List<String> dependencyFields =
Arrays.asList("dependencies", "devDependencies", "peerDependencies");
packageJsonFiles.forEach(
(path, packageJson) -> {
Path relativePath = sourceRoot.relativize(path);
for (String dependencyField : dependencyFields) {
JsonElement dependencyElm = packageJson.get(dependencyField);
if (!(dependencyElm instanceof JsonObject)) continue;
JsonObject dependencyObj = (JsonObject) dependencyElm;
List<String> propsToRemove = new ArrayList<>();
for (String packageName : dependencyObj.keySet()) {
if (packagesInRepo.containsKey(packageName)) {
// Remove dependency on local package
propsToRemove.add(packageName);
} else {
// Remove file dependency on a package that doesn't exist in the checkout.
String dependency = getChildAsString(dependencyObj, packageName);
if (dependency != null && (dependency.startsWith("file:") || dependency.startsWith("./") || dependency.startsWith("../"))) {
if (dependency.startsWith("file:")) {
dependency = dependency.substring("file:".length());
}
Path resolvedPackage = path.getParent().resolve(dependency + "/package.json");
if (!Files.exists(resolvedPackage)) {
propsToRemove.add(packageName);
}
}
}
}
for (String prop : propsToRemove) {
dependencyObj.remove(prop);
}
}
// For named packages, find the main file.
String name = getChildAsString(packageJson, "name");
if (name != null) {
Path entryPoint = guessPackageMainFile(path, packageJson, FileType.TYPESCRIPT.getExtensions());
if (entryPoint == null) {
// Try a TypeScript-recognized JS extension instead
entryPoint = guessPackageMainFile(path, packageJson, Arrays.asList(".js", ".jsx"));
}
if (entryPoint != null) {
System.out.println(relativePath + ": Main file set to " + sourceRoot.relativize(entryPoint));
packageMainFile.put(name, entryPoint);
} else {
System.out.println(relativePath + ": Main file not found");
}
}
});
// Write the new package.json files to disk
for (Path file : packageJsonFiles.keySet()) {
Path virtualFile = virtualSourceRoot.toVirtualFile(file);
try {
Files.createDirectories(virtualFile.getParent());
try (Writer writer = Files.newBufferedWriter(virtualFile)) {
new Gson().toJson(packageJsonFiles.get(file), writer);
}
} catch (IOException e) {
throw new ResourceError("Could not rewrite package.json file: " + virtualFile, e);
}
}
// Install dependencies
if (this.installDependencies && verifyYarnInstallation()) {
for (Path file : packageJsonFiles.keySet()) {
Path virtualFile = virtualSourceRoot.toVirtualFile(file);
System.out.println("Installing dependencies from " + virtualFile);
ProcessBuilder pb =
new ProcessBuilder(
Arrays.asList(
"yarn",
"install",
"--non-interactive",
"--ignore-scripts",
"--ignore-platform",
"--ignore-engines",
"--ignore-optional",
"--no-default-rc",
"--no-bin-links",
"--pure-lockfile"));
pb.directory(virtualFile.getParent().toFile());
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
try {
pb.start().waitFor(this.installDependenciesTimeout, TimeUnit.MILLISECONDS);
} catch (IOException | InterruptedException ex) {
throw new ResourceError("Could not install dependencies from " + file, ex);
}
}
}
return new DependencyInstallationResult(packageMainFile, packagesInRepo);
}
/**
* Attempts to find a TypeScript file that acts as the main entry point to the
* given package - that is, the file you get when importing the package by name
* without any path suffix.
*/
private Path guessPackageMainFile(Path packageJsonFile, JsonObject packageJson, Iterable<String> extensions) {
Path packageDir = packageJsonFile.getParent();
// Try <package_dir>/index.ts.
Path resolved = tryResolveWithExtensions(packageDir, "index", extensions);
if (resolved != null) {
return resolved;
}
// Get the "main" property from the package.json
// This usually refers to the compiled output, such as `./out/foo.js` but may hint as to
// the name of main file ("foo" in this case).
String mainStr = getChildAsString(packageJson, "main");
// Look for source files `./src` if it exists
Path sourceDir = packageDir.resolve("src");
if (Files.isDirectory(sourceDir)) {
// Try `src/index.ts`
resolved = tryResolveTypeScriptOrJavaScriptFile(sourceDir, "index");
if (resolved != null) {
return resolved;
}
// If "main" was defined, try to map it to a file in `src`.
// For example `out/dist/foo.bundle.js` might be mapped back to `src/foo.ts`.
if (mainStr != null) {
Path candidatePath = Paths.get(mainStr);
// Strip off prefix directories that don't exist under `src/`, such as `out` and `dist`.
while (candidatePath.getNameCount() > 1 && !Files.isDirectory(sourceDir.resolve(candidatePath.getParent()))) {
candidatePath = candidatePath.subpath(1, candidatePath.getNameCount());
}
// Strip off extensions until a file can be found
while (true) {
resolved = tryResolveWithExtensions(sourceDir, candidatePath.toString(), extensions);
if (resolved != null) {
return resolved;
}
Path withoutExt = candidatePath.resolveSibling(FileUtil.stripExtension(candidatePath.getFileName().toString()));
if (withoutExt.equals(candidatePath)) break; // No more extensions to strip
candidatePath = withoutExt;
}
}
}
// Try to resolve main as a sibling of the package.json file, such as "./main.js" -> "./main.ts".
if (mainStr != null) {
Path mainPath = Paths.get(mainStr);
String withoutExt = FileUtil.stripExtension(mainPath.getFileName().toString());
resolved = tryResolveWithExtensions(packageDir, withoutExt, extensions);
if (resolved != null) {
return resolved;
}
}
return null;
}
private ExtractorConfig mkExtractorConfig() {
ExtractorConfig config = new ExtractorConfig(true);
config = config.withSourceType(getSourceType());
config = config.withTypeScriptMode(typeScriptMode);
config = config.withVirtualSourceRoot(virtualSourceRoot);
if (defaultEncoding != null) config = config.withDefaultEncoding(defaultEncoding);
return config;
}
private Set<Path> extractTypeScript(
Set<Path> files,
Set<Path> extractedFiles,
FileExtractors extractors,
List<Path> tsconfig,
DependencyInstallationResult deps) {
if (hasTypeScriptFiles(files) || !tsconfig.isEmpty()) {
TypeScriptParser tsParser = state.getTypeScriptParser();
verifyTypeScriptInstallation(state);
// Collect all files included in a tsconfig.json inclusion pattern.
// If a given file is referenced by multiple tsconfig files, we prefer to extract it using
// one that includes it rather than just references it.
Set<File> explicitlyIncludedFiles = new LinkedHashSet<>();
if (tsconfig.size() > 1) { // No prioritization needed if there's only one tsconfig.
for (Path projectPath : tsconfig) {
explicitlyIncludedFiles.addAll(tsParser.getOwnFiles(projectPath.toFile(), deps, virtualSourceRoot));
}
}
// Extract TypeScript projects
for (Path projectPath : tsconfig) {
File projectFile = projectPath.toFile();
long start = logBeginProcess("Opening project " + projectFile);
ParsedProject project = tsParser.openProject(projectFile, deps, virtualSourceRoot);
logEndProcess(start, "Done opening project " + projectFile);
// Extract all files belonging to this project which are also matched
// by our include/exclude filters.
List<Path> typeScriptFiles = new ArrayList<Path>();
for (File sourceFile : project.getAllFiles()) {
Path sourcePath = sourceFile.toPath();
Path normalizedFile = normalizePath(sourcePath);
if (!files.contains(normalizedFile) && !state.getSnippets().containsKey(normalizedFile)) {
continue;
}
if (!project.getOwnFiles().contains(sourceFile) && explicitlyIncludedFiles.contains(sourceFile)) continue;
if (extractors.fileType(sourcePath) != FileType.TYPESCRIPT) {
// For the time being, skip non-TypeScript files, even if the TypeScript
// compiler can parse them for us.
continue;
}
if (!extractedFiles.contains(sourcePath)) {
typeScriptFiles.add(sourcePath);
}
}
typeScriptFiles.sort(PATH_ORDERING);
extractTypeScriptFiles(typeScriptFiles, extractedFiles, extractors);
tsParser.closeProject(projectFile);
}
// Extract all the types discovered when extracting the ASTs.
if (!tsconfig.isEmpty()) {
TypeTable typeTable = tsParser.getTypeTable();
extractTypeTable(tsconfig.iterator().next(), typeTable);
}
// Extract remaining TypeScript files.
List<Path> remainingTypeScriptFiles = new ArrayList<>();
for (Path f : files) {
if (!extractedFiles.contains(f)
&& extractors.fileType(f) == FileType.TYPESCRIPT) {
remainingTypeScriptFiles.add(f);
}
}
if (!remainingTypeScriptFiles.isEmpty()) {
extractTypeScriptFiles(remainingTypeScriptFiles, extractedFiles, extractors);
}
// The TypeScript compiler instance is no longer needed.
tsParser.killProcess();
}
return extractedFiles;
}
private boolean hasTypeScriptFiles(Set<Path> filesToExtract) {
for (Path file : filesToExtract) {
// Check if there are any files with the TypeScript extension.
// Do not use FileType.forFile as it involves I/O for file header checks,
// and files with a bad header have already been excluded.
if (FileType.forFileExtension(file.toFile()) == FileType.TYPESCRIPT) return true;
}
return false;
}
private void findFilesToExtract(
FileExtractor extractor, final Set<Path> filesToExtract, final List<Path> tsconfigFiles)
throws IOException {
Path[] currentRoot = new Path[1];
FileVisitor<? super Path> visitor =
new SimpleFileVisitor<Path>() {
private boolean isFileIncluded(Path file) {
// normalise path for matching
String path = file.toString().replace('\\', '/');
if (path.charAt(0) != '/') path = "/" + path;
return filters.includeFile(path);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (attrs.isSymbolicLink()) return FileVisitResult.SKIP_SUBTREE;
if (!file.equals(currentRoot[0]) && excludes.contains(file))
return FileVisitResult.SKIP_SUBTREE;
// extract files that are supported and pass the include/exclude patterns
boolean supported = extractor.supports(file.toFile());
if (!supported && !fileTypes.isEmpty()) {
supported = fileTypes.containsKey(FileUtil.extension(file));
}
if (supported && isFileIncluded(file)) {
filesToExtract.add(normalizePath(file));
}
// extract TypeScript projects from 'tsconfig.json'
if (typeScriptMode == TypeScriptMode.FULL
&& file.getFileName().endsWith("tsconfig.json")
&& !excludes.contains(file)
&& isFileIncluded(file)) {
tsconfigFiles.add(file);
}
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
if (!dir.equals(currentRoot[0]) && (excludes.contains(dir) || dir.toFile().isHidden()))
return FileVisitResult.SKIP_SUBTREE;
if (Files.exists(dir.resolve("codeql-database.yml"))) {
return FileVisitResult.SKIP_SUBTREE;
}
return super.preVisitDirectory(dir, attrs);
}
};
for (Path root : includes) {
currentRoot[0] = root;
Files.walkFileTree(currentRoot[0], visitor);
}
}
/** Verifies that Node.js and the TypeScript compiler are installed and can be found. */
public void verifyTypeScriptInstallation(ExtractorState extractorState) {
extractorState.getTypeScriptParser().verifyInstallation(true);
}
public void extractTypeScriptFiles(
List<Path> files,
Set<Path> extractedFiles,
FileExtractors extractors) {
List<File> list = files
.stream()
.sorted(PATH_ORDERING)
.map(p -> p.toFile()).collect(Collectors.toList());
state.getTypeScriptParser().prepareFiles(list);
for (Path path : files) {
extractedFiles.add(path);
extract(extractors.forFile(path), path, false);
}
}
private Path normalizePath(Path path) {
return path.toAbsolutePath().normalize();
}
private void extractTypeTable(Path fileHandle, TypeTable table) {
TrapWriter trapWriter =
outputConfig
.getTrapWriterFactory()
.mkTrapWriter(new File(fileHandle.toString() + ".codeql-typescript-typetable"));
try {
new TypeExtractor(trapWriter, table).extract();
} finally {
FileUtil.close(trapWriter);
}
}
/**
* Get the source type specified in <code>LGTM_INDEX_SOURCE_TYPE</code>, or the default of {@link
* SourceType#AUTO}.
*/
private SourceType getSourceType() {
String sourceTypeName = getEnvVar("LGTM_INDEX_SOURCE_TYPE");
if (sourceTypeName != null) {
try {
return SourceType.valueOf(StringUtil.uc(sourceTypeName));
} catch (IllegalArgumentException e) {
Exceptions.ignore(e, "We construct a better error message.");
throw new UserError(sourceTypeName + " is not a valid source type.");
}
}
return SourceType.AUTO;
}
/**
* Extract a single file using the given extractor and state.
*
* <p>If the state is {@code null}, the extraction job will be submitted to the {@link
* #threadPool}, otherwise extraction will happen on the main thread.
*/
protected CompletableFuture<?> extract(FileExtractor extractor, Path file, boolean concurrent) {
if (concurrent && threadPool != null) {
return CompletableFuture.runAsync(() -> doExtract(extractor, file, state), threadPool);
} else {
doExtract(extractor, file, state);
return CompletableFuture.completedFuture(null);
}
}
private void doExtract(FileExtractor extractor, Path file, ExtractorState state) {
File f = file.toFile();
if (!f.exists()) {
warn("Skipping " + file + ", which does not exist.");
return;
}
try {
long start = logBeginProcess("Extracting " + file);
Integer loc = extractor.extract(f, state);
if (!extractor.getConfig().isExterns() && (loc == null || loc != 0)) seenCode = true;
if (!extractor.getConfig().isExterns()) seenFiles = true;
logEndProcess(start, "Done extracting " + file);
} catch (Throwable t) {
System.err.println("Exception while extracting " + file + ".");
t.printStackTrace(System.err);
System.exit(1);
}
}
private void warn(String msg) {
System.err.println(msg);
System.err.flush();
}
private long logBeginProcess(String message) {
System.out.println(message);
return System.nanoTime();
}
private void logEndProcess(long timedLogMessageStart, String message) {
long end = System.nanoTime();
int milliseconds = (int) ((end - timedLogMessageStart) / 1_000_000);
System.out.println(message + " (" + milliseconds + " ms)");
System.out.flush();
}
public Set<String> getXmlExtensions() {
return xmlExtensions;
}
protected void extractXml() throws IOException {
if (xmlExtensions.isEmpty()) return;
List<String> cmd = new ArrayList<>();
cmd.add("odasa");
cmd.add("index");
cmd.add("--xml");
cmd.add("--extensions");
cmd.addAll(xmlExtensions);
ProcessBuilder pb = new ProcessBuilder(cmd);
try {
pb.redirectError(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
pb.start().waitFor();
} catch (InterruptedException e) {
throw new CatastrophicError(e);
}
}
public static void main(String[] args) {
try {
System.exit(new AutoBuild().run());
} catch (IOException | UserError | CatastrophicError e) {
System.err.println(e.toString());
System.exit(1);
}
}
}
| 52,090 | 40.14613 | 140 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/SyntacticContextManager.java | package com.semmle.js.extractor;
import com.semmle.js.ast.BreakStatement;
import com.semmle.js.ast.JumpStatement;
import com.semmle.js.ast.LabeledStatement;
import com.semmle.js.ast.Loop;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.SwitchStatement;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* The syntactic context manager keeps track of the statement currently being extracted and its
* enclosing loops, switch statements and labelled statements. It can use this information to
* determine the targets of 'break' or 'continue' statements.
*
* <p>The syntactic context manager maintains a context chain. Each context object on the chain
* represents a syntactic context within a given function or the toplevel, and has a link to its
* enclosing syntactic context. Context objects also maintain a reference to the statement currently
* being extracted, and to the function or toplevel.
*
* <p>Furthermore, each context object has two maps, one representing 'break' targets, the other
* 'continue' targets. These maps associate labels <i>l</i> with the nearest enclosing statement (in
* the same function) that has label <i>l</i>, if any. If <i>l</i> is the empty string, it maps to
* the nearest enclosing loop or switch statement (but only for 'break' targets).
*/
public class SyntacticContextManager {
private static class JumpTarget {
private final String label;
private final Node node;
private final JumpTarget outer;
public JumpTarget(String label, Node node, JumpTarget outer) {
this.label = label;
this.node = node;
this.outer = outer;
}
public Node lookup(String label) {
if (this.label.equals(label)) return node;
return outer == null ? null : outer.lookup(label);
}
}
private static class Context {
private final Context outer;
private final Label containerKey;
private Statement curStatement;
private JumpTarget breakTargets;
private JumpTarget continueTargets;
public Context(Context outer, Label containerKey) {
this.outer = outer;
this.containerKey = containerKey;
}
public void addBreakTarget(String label, Node node) {
breakTargets = new JumpTarget(label, node, breakTargets);
}
public void addContinueTarget(String label, Node node) {
continueTargets = new JumpTarget(label, node, continueTargets);
}
}
private Context context = null;
private final Set<LabeledStatement> loopLabels = new LinkedHashSet<LabeledStatement>();
public void enterContainer(Label containerKey) {
context = new Context(context, containerKey);
}
public void leaveContainer() {
context = context.outer;
}
public Statement getCurrentStatement() {
return context.curStatement;
}
public void setCurrentStatement(Statement nd) {
context.curStatement = nd;
}
public Object getCurrentContainerKey() {
return context.containerKey;
}
public void enterSwitchStatement(SwitchStatement nd) {
context.addBreakTarget("", nd);
}
public void leaveSwitchStatement() {
context.breakTargets = context.breakTargets.outer;
}
public void enterLoopStmt(Statement nd) {
context.addBreakTarget("", nd);
context.addContinueTarget("", nd);
}
public void leaveLoopStmt() {
context.breakTargets = context.breakTargets.outer;
context.continueTargets = context.continueTargets.outer;
}
public void enterLabeledStatement(LabeledStatement nd) {
context.addBreakTarget(nd.getLabel().getName(), nd);
// check whether this labelled statement directly or indirectly labels a loop
// (and thus may be the target of a 'continue' statement)
Statement stmt;
for (stmt = nd.getBody(); stmt instanceof LabeledStatement; ) {
stmt = ((LabeledStatement) stmt).getBody();
}
if (stmt instanceof Loop) {
loopLabels.add(nd);
context.addContinueTarget(nd.getLabel().getName(), nd);
}
}
public void leaveLabeledStatement(LabeledStatement nd) {
context.breakTargets = context.breakTargets.outer;
if (loopLabels.contains(nd)) context.continueTargets = context.continueTargets.outer;
}
public Object getTarget(JumpStatement nd) {
String label = nd.hasLabel() ? nd.getLabel().getName() : "";
if (nd instanceof BreakStatement)
return this.context.breakTargets == null ? null : this.context.breakTargets.lookup(label);
else
return this.context.continueTargets == null
? null
: this.context.continueTargets.lookup(label);
}
}
| 4,638 | 32.135714 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/FileSnippet.java | package com.semmle.js.extractor;
import java.nio.file.Path;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
/**
* Denotes where a code snippet originated from within a file.
*/
public class FileSnippet {
private Path originalFile;
private int line;
private int column;
private int topLevelKind;
private SourceType sourceType;
public FileSnippet(Path originalFile, int line, int column, int topLevelKind, SourceType sourceType) {
this.originalFile = originalFile;
this.line = line;
this.column = column;
this.topLevelKind = topLevelKind;
this.sourceType = sourceType;
}
public Path getOriginalFile() {
return originalFile;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
public int getTopLevelKind() {
return topLevelKind;
}
public SourceType getSourceType() {
return sourceType;
}
}
| 913 | 19.311111 | 104 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/JumpType.java | package com.semmle.js.extractor;
/** Simple enum for representing the four kinds of unstructured control flow in JavaScript. */
public enum JumpType {
BREAK,
CONTINUE,
THROW,
RETURN;
}
| 194 | 18.5 | 94 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/TypeScriptExtractor.java | package com.semmle.js.extractor;
import java.io.File;
import com.semmle.js.extractor.ExtractorConfig.ECMAVersion;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.parser.JSParser.Result;
import com.semmle.js.parser.ParseError;
public class TypeScriptExtractor implements IExtractor {
private final JSExtractor jsExtractor;
private final ExtractorState state;
public TypeScriptExtractor(ExtractorConfig config, ExtractorState state) {
this.jsExtractor = new JSExtractor(config);
this.state = state;
}
@Override
public LoCInfo extract(TextualExtractor textualExtractor) {
LocationManager locationManager = textualExtractor.getLocationManager();
String source = textualExtractor.getSource();
File sourceFile = textualExtractor.getExtractedFile();
Result res = state.getTypeScriptParser().parse(sourceFile, source, textualExtractor.getMetrics());
ScopeManager scopeManager =
new ScopeManager(textualExtractor.getTrapwriter(), ECMAVersion.ECMA2017);
try {
FileSnippet snippet = state.getSnippets().get(sourceFile.toPath());
SourceType sourceType = snippet != null ? snippet.getSourceType() : jsExtractor.establishSourceType(source, false);
int toplevelKind = snippet != null ? snippet.getTopLevelKind() : 0;
return jsExtractor.extract(textualExtractor, source, toplevelKind, scopeManager, sourceType, res).snd();
} catch (ParseError e) {
e.setPosition(locationManager.translatePosition(e.getPosition()));
throw e.asUserError();
}
}
}
| 1,563 | 40.157895 | 121 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/CFGExtractor.java | package com.semmle.js.extractor;
import com.semmle.js.ast.AClass;
import com.semmle.js.ast.AFunctionExpression;
import com.semmle.js.ast.ArrayExpression;
import com.semmle.js.ast.ArrayPattern;
import com.semmle.js.ast.AssignmentExpression;
import com.semmle.js.ast.AwaitExpression;
import com.semmle.js.ast.BinaryExpression;
import com.semmle.js.ast.BindExpression;
import com.semmle.js.ast.BlockStatement;
import com.semmle.js.ast.BreakStatement;
import com.semmle.js.ast.CallExpression;
import com.semmle.js.ast.CatchClause;
import com.semmle.js.ast.Chainable;
import com.semmle.js.ast.ClassBody;
import com.semmle.js.ast.ClassDeclaration;
import com.semmle.js.ast.ClassExpression;
import com.semmle.js.ast.ComprehensionBlock;
import com.semmle.js.ast.ComprehensionExpression;
import com.semmle.js.ast.ConditionalExpression;
import com.semmle.js.ast.Decorator;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.DestructuringPattern;
import com.semmle.js.ast.DoWhileStatement;
import com.semmle.js.ast.DynamicImport;
import com.semmle.js.ast.EnhancedForStatement;
import com.semmle.js.ast.ExportAllDeclaration;
import com.semmle.js.ast.ExportDefaultDeclaration;
import com.semmle.js.ast.ExportDefaultSpecifier;
import com.semmle.js.ast.ExportNamedDeclaration;
import com.semmle.js.ast.ExportNamespaceSpecifier;
import com.semmle.js.ast.ExportSpecifier;
import com.semmle.js.ast.Expression;
import com.semmle.js.ast.ExpressionStatement;
import com.semmle.js.ast.FieldDefinition;
import com.semmle.js.ast.ForStatement;
import com.semmle.js.ast.FunctionDeclaration;
import com.semmle.js.ast.IFunction;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.IStatementContainer;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.IfStatement;
import com.semmle.js.ast.ImportDeclaration;
import com.semmle.js.ast.ImportSpecifier;
import com.semmle.js.ast.InvokeExpression;
import com.semmle.js.ast.JumpStatement;
import com.semmle.js.ast.LabeledStatement;
import com.semmle.js.ast.LetExpression;
import com.semmle.js.ast.LetStatement;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.LogicalExpression;
import com.semmle.js.ast.Loop;
import com.semmle.js.ast.MemberDefinition;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.ast.MethodDefinition;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.ObjectExpression;
import com.semmle.js.ast.ObjectPattern;
import com.semmle.js.ast.ParenthesizedExpression;
import com.semmle.js.ast.Program;
import com.semmle.js.ast.Property;
import com.semmle.js.ast.ReturnStatement;
import com.semmle.js.ast.SequenceExpression;
import com.semmle.js.ast.SourceLocation;
import com.semmle.js.ast.SpreadElement;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.Super;
import com.semmle.js.ast.SwitchCase;
import com.semmle.js.ast.SwitchStatement;
import com.semmle.js.ast.TaggedTemplateExpression;
import com.semmle.js.ast.TemplateLiteral;
import com.semmle.js.ast.ThrowStatement;
import com.semmle.js.ast.TryStatement;
import com.semmle.js.ast.UnaryExpression;
import com.semmle.js.ast.UpdateExpression;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.js.ast.VariableDeclarator;
import com.semmle.js.ast.Visitor;
import com.semmle.js.ast.WhileStatement;
import com.semmle.js.ast.WithStatement;
import com.semmle.js.ast.XMLAnyName;
import com.semmle.js.ast.XMLAttributeSelector;
import com.semmle.js.ast.XMLDotDotExpression;
import com.semmle.js.ast.XMLFilterExpression;
import com.semmle.js.ast.XMLQualifiedIdentifier;
import com.semmle.js.ast.YieldExpression;
import com.semmle.js.ast.jsx.IJSXName;
import com.semmle.js.ast.jsx.JSXAttribute;
import com.semmle.js.ast.jsx.JSXElement;
import com.semmle.js.ast.jsx.JSXExpressionContainer;
import com.semmle.js.ast.jsx.JSXMemberExpression;
import com.semmle.js.ast.jsx.JSXNamespacedName;
import com.semmle.js.ast.jsx.JSXOpeningElement;
import com.semmle.js.ast.jsx.JSXSpreadAttribute;
import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase;
import com.semmle.ts.ast.DecoratorList;
import com.semmle.ts.ast.EnumDeclaration;
import com.semmle.ts.ast.EnumMember;
import com.semmle.ts.ast.ExportWholeDeclaration;
import com.semmle.ts.ast.ExpressionWithTypeArguments;
import com.semmle.ts.ast.ExternalModuleReference;
import com.semmle.ts.ast.ImportWholeDeclaration;
import com.semmle.ts.ast.NamespaceDeclaration;
import com.semmle.ts.ast.NonNullAssertion;
import com.semmle.ts.ast.TypeAssertion;
import com.semmle.util.collections.CollectionUtil;
import com.semmle.util.data.Pair;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
/**
* Extractor for intra-procedural expression-level control flow graphs.
*
* <p>The nodes in the CFG are expressions, statements, and synthetic entry and exit nodes for every
* function and for every toplevel.
*
* <p>Exceptional control flow is modeled (mostly) conservatively inside `try`-`catch`, i.e., most
* syntactic constructs that can throw an exception at runtime will get a CFG edge to the enclosing
* `catch`. We do not model the possible exception resulting from accessing an undeclared global
* variable, or possible exceptions thrown by implicitly invoked conversion methods.
*
* <p>Outside `try`-`catch`, only `throw` statements have their exceptional control flow modeled:
* they have the `exit` node of the enclosing function or toplevel as their successor.
*
* <p>Control flow through `finally` is modeled imprecisely: there is only a single copy of each
* `finally` block in the CFG, so different control flow paths through a `finally` block get merged
* at the block.
*
* <p>The control flow inside compound expressions and statements reflects execution order at
* runtime. For most statements that contain expressions, the statement appears in the CFG before
* the contained expression. The two exceptions here are `return` and `throw`, which both appear
* _after_ the contained expression to reflect the fact that the return/throw happens after the
* expression has been evaluated.
*
* <p>For assignments, we take the assignment expression itself to express the operation of
* assigning the RHS to the LHS. Thus, in a simple assignment expression of the form `lhs = rhs`,
* the control flow is lhs -> rhs -> lhs = rhs.
*
* <p>For most binary expressions, the expression node itself represents the operator application,
* so the CFG of `x + y` is x -> y -> x + y. For short-circuiting operators, on the other
* hand, the expression node itself acts more like an `if` statement, hence it comes first in the
* CFG: `x && y` has CFG
*
* <p>x && y +> x -> y +> f |_________|
*
* <p>Finally, for a variable declarator with an initialiser, the declarator represents the
* assignment of the initialiser expression to the variable. So, the CFG of `var x = 23` is x ->
* 23 -> var x = 23.
*
* <p>The CFG of each function starts with a preamble that visits the parameters and, for ECMAScript
* 2015 and above, their default arguments, followed by the identifiers of each function declaration
* in the body in lexical order. This reflects the fact that function declarations are hoisted, but
* their initialisation happens after parameters have been assigned.
*
* <p>Similar considerations apply to toplevels: the preamble visits any import specifiers first,
* reflecting the fact that imports are resolved before module evaluation starts, followed by (the
* identifiers of) hoisted function declarations.
*/
public class CFGExtractor {
private final TrapWriter trapwriter;
private final Label toplevelLabel;
private final LocationManager locationManager;
private final ExtractionMetrics metrics;
public CFGExtractor(ASTExtractor astExtractor) {
this.trapwriter = astExtractor.getTrapwriter();
this.toplevelLabel = astExtractor.getToplevelLabel();
this.locationManager = astExtractor.getLocationManager();
this.metrics = astExtractor.getMetrics();
}
@SuppressWarnings("unchecked")
private static Iterable<Node> foreach(Object nd) {
if (nd == null) return Collections.<Node>emptySet();
if (nd instanceof Node) return CollectionUtil.singletonIterable((Node) nd);
return (Iterable<Node>) nd;
}
private Iterable<Node> hcaerof(final Object nd) {
if (nd == null) return Collections.<Node>emptySet();
if (nd instanceof Node) return CollectionUtil.singletonIterable((Node) nd);
return new Iterable<Node>() {
@SuppressWarnings("unchecked")
@Override
public Iterator<Node> iterator() {
return CollectionUtil.reverseIterator((List<Node>) nd);
}
};
}
/** Returns a list of all the nodes in a tree of nested lists. */
private List<Node> flattenNestedList(Iterable<?> lists) {
return flattenNestedList(lists, new ArrayList<>());
}
/**
* Appends all the nodes in a tree of nested lists the given output list, and returns that list.
*/
private List<Node> flattenNestedList(Iterable<?> lists, List<Node> output) {
for (Object object : lists) {
if (object == null) continue;
if (object instanceof Node) {
output.add((Node) object);
} else if (object instanceof Iterable<?>) {
flattenNestedList((Iterable<?>) object, output);
} else {
throw new RuntimeException("Cannot flatten object: " + object);
}
}
return output;
}
private static Object union(Object xs, Object ys) {
if (xs == null) return ys;
if (ys == null) return xs;
if (xs instanceof List<?>) {
@SuppressWarnings("unchecked")
List<Node> xsCopy = new ArrayList<Node>((List<Node>) xs);
for (Node y : foreach(ys)) if (!xsCopy.contains(y)) xsCopy.add(y);
return xsCopy;
} else {
if (ys instanceof List<?>) {
@SuppressWarnings("unchecked")
List<Object> lys = (List<Object>) ys;
if (!lys.contains(xs)) {
lys = new ArrayList<Object>(lys);
lys.add(0, xs);
}
return lys;
} else if (xs == ys) {
return xs;
} else {
List<Node> res = new ArrayList<Node>(2);
res.add((Node) xs);
res.add((Node) ys);
return res;
}
}
}
private void succ(Object nd, Object succs) {
Label ndkey = trapwriter.localID(nd);
for (Node succ : foreach(succs)) succ(ndkey, succ);
}
private void succ(Label ndkey, Node succ) {
trapwriter.addTuple("successor", ndkey, trapwriter.localID(succ));
}
/**
* Compute the first sub-expression or sub-statement in control flow order.
*
* <p>Caution: If you modify this, be sure to also adjust the implementation of the corresponding
* QL-level method ExprParent.getFirstControlFlowNode().
*/
private static class First extends DefaultVisitor<Void, Node> {
@Override
public Node visit(Node nd, Void v) {
return nd;
}
@Override
public Node visit(ReturnStatement nd, Void v) {
if (nd.hasArgument()) return nd.getArgument().accept(this, v);
else return nd;
}
@Override
public Node visit(ThrowStatement nd, Void v) {
return nd.getArgument().accept(this, v);
}
@Override
public Node visit(SpreadElement nd, Void v) {
return nd.getArgument().accept(this, v);
}
@Override
public Node visit(UnaryExpression nd, Void v) {
return nd.getArgument().accept(this, v);
}
@Override
public Node visit(UpdateExpression nd, Void v) {
return nd.getArgument().accept(this, v);
}
@Override
public Node visit(YieldExpression nd, Void v) {
Expression argument = nd.getArgument();
if (argument != null) return argument.accept(this, v);
return nd;
}
@Override
public Node visit(Property nd, Void v) {
Expression key = nd.getKey();
return (key == null ? nd.getValue() : key).accept(this, v);
}
@Override
public Node visit(MemberDefinition<?> nd, Void v) {
if (!nd.isConcrete() || nd.isParameterField()) return nd;
return nd.getKey().accept(this, v);
}
// for binary operators, the operands come first (but not for short-circuiting expressions), see
// above)
@Override
public Node visit(BinaryExpression nd, Void v) {
if ("??".equals(nd.getOperator())) return nd;
return nd.getLeft().accept(this, v);
}
@Override
public Node visit(AssignmentExpression nd, Void v) {
if (nd.getLeft() instanceof DestructuringPattern) return nd.getRight().accept(this, v);
return nd.getLeft().accept(this, v);
}
@Override
public Node visit(VariableDeclarator nd, Void v) {
if (nd.getId() instanceof DestructuringPattern && nd.hasInit())
return nd.getInit().accept(this, v);
return nd.getId().accept(this, v);
}
@Override
public Node visit(MemberExpression nd, Void v) {
return nd.getObject().accept(this, v);
}
@Override
public Node visit(InvokeExpression nd, Void v) {
return nd.getCallee().accept(this, v);
}
@Override
public Node visit(JSXElement nd, Void v) {
IJSXName name = nd.getOpeningElement().getName();
if (name == null) {
if (nd.getChildren().isEmpty()) return nd;
return nd.getChildren().get(0).accept(this, v);
}
return name.accept(this, v);
}
@Override
public Node visit(JSXMemberExpression nd, Void v) {
return nd.getObject().accept(this, v);
}
@Override
public Node visit(JSXNamespacedName nd, Void v) {
return nd.getNamespace().accept(this, v);
}
@Override
public Node visit(JSXAttribute nd, Void v) {
return nd.getName().accept(this, v);
}
@Override
public Node visit(JSXSpreadAttribute nd, Void v) {
return nd.getArgument().accept(this, v);
}
@Override
public Node visit(JSXExpressionContainer nd, Void v) {
return nd.getExpression().accept(this, v);
}
@Override
public Node visit(AwaitExpression nd, Void c) {
return nd.getArgument().accept(this, c);
}
@Override
public Node visit(Decorator nd, Void v) {
return nd.getExpression().accept(this, v);
}
@Override
public Node visit(BindExpression nd, Void v) {
if (nd.hasObject()) return nd.getObject().accept(this, v);
return nd.getCallee().accept(this, v);
}
@Override
public Node visit(ExternalModuleReference nd, Void v) {
return nd.getExpression().accept(this, v);
}
@Override
public Node visit(DynamicImport nd, Void v) {
return nd.getSource().accept(this, v);
}
@Override
public Node visit(ClassDeclaration nd, Void v) {
if (nd.hasDeclareKeyword()) return nd;
else return nd.getClassDef().getId();
}
@Override
public Node visit(ClassExpression nd, Void v) {
AClass def = nd.getClassDef();
if (def.getId() != null) return def.getId();
if (def.getSuperClass() != null) return def.getSuperClass().accept(this, v);
Node first = def.getBody().accept(this, v);
if (first != null) return first;
return nd;
}
@Override
public Node visit(ClassBody nd, Void v) {
for (MemberDefinition<?> m : nd.getBody()) {
if (m instanceof MethodDefinition) {
Node first = m.accept(this, v);
if (first != null) return first;
}
}
return null;
}
@Override
public Node visit(ExpressionWithTypeArguments nd, Void c) {
return nd.getExpression().accept(this, c);
}
@Override
public Node visit(TypeAssertion nd, Void c) {
return nd.getExpression().accept(this, c);
}
@Override
public Node visit(NonNullAssertion nd, Void c) {
return nd.getExpression().accept(this, c);
}
@Override
public Node visit(EnumDeclaration nd, Void c) {
return nd.getId();
}
@Override
public Node visit(EnumMember nd, Void c) {
return nd.getId();
}
@Override
public Node visit(DecoratorList nd, Void c) {
if (nd.getDecorators().isEmpty()) return nd;
return nd.getDecorators().get(0).accept(this, c);
}
@Override
public Node visit(NamespaceDeclaration nd, Void c) {
if (nd.hasDeclareKeyword()) return nd;
return nd.getName();
}
@Override
public Node visit(ImportWholeDeclaration nd, Void c) {
return nd.getLhs();
}
@Override
public Node visit(EnhancedForStatement nd, Void c) {
return nd.getRight().accept(this, null);
}
@Override
public Node visit(XMLAttributeSelector nd, Void c) {
return nd.getAttribute().accept(this, c);
}
@Override
public Node visit(XMLFilterExpression nd, Void c) {
return nd.getLeft().accept(this, c);
}
@Override
public Node visit(XMLQualifiedIdentifier nd, Void c) {
return nd.getLeft().accept(this, c);
}
@Override
public Node visit(XMLDotDotExpression nd, Void c) {
return nd.getLeft().accept(this, c);
}
public static Node of(Node nd) {
return nd.accept(new First(), null);
}
}
/**
* Collect all hoisted function declaration statements (that is, function declarations not nested
* inside a block statement or control statement) in a subtree, returning an array containing
* their declaring identifiers in lexical order.
*
* <p>This is used to construct the function preamble mentioned above.
*/
private static class HoistedFunDecls extends DefaultVisitor<Void, Void> {
private List<Identifier> decls = new ArrayList<Identifier>();
@Override
public Void visit(FunctionDeclaration nd, Void v) {
// We do not consider ambient function declarations to be hoisted.
if (!nd.hasDeclareKeyword()) {
decls.add(nd.getId());
}
return null;
}
@Override
public Void visit(LabeledStatement nd, Void v) {
return nd.getBody().accept(this, v);
}
@Override
public Void visit(ExportDefaultDeclaration nd, Void c) {
return nd.getDeclaration().accept(this, c);
}
@Override
public Void visit(ExportNamedDeclaration nd, Void c) {
if (nd.hasDeclaration()) nd.getDeclaration().accept(this, c);
return null;
}
private static List<Identifier> of(List<Statement> body) {
HoistedFunDecls d = new HoistedFunDecls();
for (Node stmt : body) stmt.accept(d, null);
return d.decls;
}
public static List<Identifier> of(Program p) {
return of(p.getBody());
}
public static List<Identifier> of(IFunction fn) {
Node body = fn.getBody();
if (body instanceof BlockStatement) return of(((BlockStatement) body).getBody());
// if the body of the function is missing or is an expression, then there are
// no hoisted functions
return Collections.emptyList();
}
}
/**
* Class used to represent information about the possible successors of a CFG node during
* extraction.
*
* <p>For expressions and catch clauses, we distinguish between "true" and "false" successors (the
* former being the successors in case the expression or catch guard evaluates to a truthy value,
* the latter the successors for the falsy case); for other CFG nodes, no such distinction is
* made.
*/
private abstract static class SuccessorInfo {
/**
* Get all possible successors, including both "true" and "false" successors where applicable.
*/
public abstract Object getAllSuccessors();
/**
* Depending on the value of {@code edge}, get only the "true" or only the "false" successors
* (if they are not distinguished, the same set will be returned in both cases.)
*/
public abstract Object getSuccessors(boolean edge);
/**
* If we have both true and false successors, place guard nodes before them indicating that
* <code>guard</code> is true or false, respectively, and return the set containing all guarded
* successors.
*
* <p>Otherwise, just return the set of all successors.
*/
public abstract Object getGuardedSuccessors(Expression guard);
}
/**
* A simple implementation of {@link SuccessorInfo} that does not distinguish between "true" and
* "false" successors.
*/
private static class SimpleSuccessorInfo extends SuccessorInfo {
private final Object successors;
public SimpleSuccessorInfo(Object successors) {
this.successors = successors;
}
@Override
public Object getAllSuccessors() {
return successors;
}
@Override
public Object getSuccessors(boolean edge) {
return successors;
}
@Override
public Object getGuardedSuccessors(Expression guard) {
return successors;
}
}
/**
* An implementation of {@link SuccessorInfo} that does distinguish between "true" and "false"
* successors.
*/
private class SplitSuccessorInfo extends SuccessorInfo {
private final Object trueSuccessors;
private final Object falseSuccessors;
public SplitSuccessorInfo(Object trueSuccessors, Object falseSuccessors) {
this.trueSuccessors = trueSuccessors;
this.falseSuccessors = falseSuccessors;
}
@Override
public Object getSuccessors(boolean edge) {
return edge ? trueSuccessors : falseSuccessors;
}
@Override
public Object getAllSuccessors() {
return union(trueSuccessors, falseSuccessors);
}
@Override
public Object getGuardedSuccessors(Expression guard) {
Object trueGuard = addGuard(guard, true, trueSuccessors);
Object falseGuard = addGuard(guard, false, falseSuccessors);
return union(trueGuard, falseGuard);
}
}
/**
* Create a guard node stating that {@code test} evaluates to {@code outcome}, with {@code succs}
* as its successors.
*
* <p>We simplify guards based on the shape of {@code test}:
*
* <ul>
* <li>If {@code test} is a parenthesised expression {@code (a)}, we create a guard for {@code
* a} instead.
* <li>If {@code test} is a negated expression {@code !a}, we create the inverse guard for
* {@code a} instead.
* <li>If {@code test} is a sequence expression {@code a, b}, we create a guard for {@code b}
* instead.
* <li>Instead of asserting that {@code a && b} is {@code true}, we assert that {@code a} and
* {@code b} are {@code true}.
* <li>Instead of asserting that {@code a || b} is {@code false}, we assert that {@code a} and
* {@code b} are {@code false}.
* <li>We never assert that {@code a && b} is {@code false} or {@code a || b} is {@code true},
* since by themselves these guards are not very useful.
* </ul>
*
* It might seem that we do not need to do this simplification since guards are placed bottom-up.
* However, the CFG for a logical negation <code>!a</code> is <code>a -> !a</code>, that is,
* <code>a</code> only has a single successor and does not immediately induce any guard nodes. We
* can only add a guard for the entire <code>!a</code> expression, at which point we will try to
* recover a condition involving <code>a</code> if possible.
*/
private Object addGuard(Expression test, boolean outcome, Object succs) {
if (test instanceof ParenthesizedExpression)
return addGuard(((ParenthesizedExpression) test).getExpression(), outcome, succs);
if (test instanceof UnaryExpression && "!".equals(((UnaryExpression) test).getOperator()))
return addGuard(((UnaryExpression) test).getArgument(), !outcome, succs);
if (test instanceof LogicalExpression) {
LogicalExpression log = (LogicalExpression) test;
String op = log.getOperator();
if (outcome && "&&".equals(op)) {
return addGuard(log.getLeft(), outcome, addGuard(log.getRight(), outcome, succs));
} else if (!outcome && "||".equals(op)) {
return addGuard(log.getLeft(), outcome, addGuard(log.getRight(), outcome, succs));
} else {
return succs;
}
}
if (test instanceof SequenceExpression) {
SequenceExpression seq = (SequenceExpression) test;
List<Expression> exprs = seq.getExpressions();
return addGuard(exprs.get(exprs.size() - 1), outcome, succs);
}
Node guardNode = guardNode(test, outcome);
succ(guardNode, succs);
return guardNode;
}
/** Generate guard nodes. */
private Node guardNode(Expression nd, boolean outcome) {
SourceLocation ndLoc = nd.getLoc();
Node result =
new Node(
"Assertion", new SourceLocation(ndLoc.getSource(), ndLoc.getStart(), ndLoc.getEnd())) {
@Override
public <Q, A> A accept(Visitor<Q, A> v, Q q) {
return null;
}
};
Label lbl = trapwriter.localID(result);
int kind = outcome ? 1 : 0;
trapwriter.addTuple("guard_node", lbl, kind, trapwriter.localID(nd));
locationManager.emitNodeLocation(result, lbl);
return result;
}
private class V extends DefaultVisitor<SuccessorInfo, Void> {
/**
* The context stores relevant bits of syntactic context to be able to resolve jumps.
*
* <p>Every element in the context is either an AST node of type `Program`,
* `FunctionDeclaration`, `FunctionExpression`, `ArrowFunctionExpression`, `WhileStatement`,
* `DoWhileStatement`, `ForStatement`, `ForInStatement`, `ForOfStatement`, `SwitchStatement`,
* `TryStatement`, `LabeledStatement` or a pseudo-node of type `Finally`. The latter means that
* we are in the `catch` clause of a `try` statement that has a `finally`.
*/
private final Stack<Node> ctxt = new Stack<Node>();
/** Hoisted function declarations in the enclosing statement container (function or script). */
private final Set<Identifier> hoistedFns = new LinkedHashSet<Identifier>();
/**
* Hoisted import declarations in the enclosing script.
*
* <p>In standard ECMAScript, all import declarations are hoisted. However, we support
* non-toplevel import declarations, which are not hoisted.
*/
private final Set<ImportDeclaration> hoistedImports = new LinkedHashSet<ImportDeclaration>();
private class Finally extends Node {
private final BlockStatement body;
public Finally(SourceLocation loc, BlockStatement body) {
super("Finally", loc);
this.body = body;
}
@Override
public <Q, A> A accept(Visitor<Q, A> v, Q q) {
return null;
}
}
// associate statements with their (direct or indirect) labels;
// per-function cache, cleared after each function
private Map<Statement, Set<String>> loopLabels = new LinkedHashMap<Statement, Set<String>>();
// cache the set of normal control flow successors;
// per-function cache, cleared after each function
private Map<Node, Object> followingCache = new LinkedHashMap<Node, Object>();
// map from a node in a chain of property accesses or calls to the successor info
// for the first node in the chain;
// per-function cache, cleared after each function
private Map<Chainable, SuccessorInfo> chainRootSuccessors =
new LinkedHashMap<Chainable, SuccessorInfo>();
/** Generate entry node. */
private final HashMap<IStatementContainer, Node> entryNodeCache =
new LinkedHashMap<IStatementContainer, Node>();
private Node entry(IStatementContainer nd) {
Node entry = entryNodeCache.get(nd);
if (entry == null) {
entry =
new Node(
"Entry", new SourceLocation("", nd.getLoc().getStart(), nd.getLoc().getStart())) {
@Override
public <Q, A> A accept(Visitor<Q, A> v, Q q) {
return null;
}
};
entryNodeCache.put(nd, entry);
Label lbl = trapwriter.localID(entry);
trapwriter.addTuple(
"entry_cfg_node", lbl, nd instanceof Program ? toplevelLabel : trapwriter.localID(nd));
locationManager.emitNodeLocation(entry, lbl);
}
return entry;
}
/** Generate exit node. */
private final HashMap<IStatementContainer, Node> exitNodeCache =
new LinkedHashMap<IStatementContainer, Node>();
private Node exit(IStatementContainer nd) {
Node exit = exitNodeCache.get(nd);
if (exit == null) {
exit =
new Node("Exit", new SourceLocation("", nd.getLoc().getEnd(), nd.getLoc().getEnd())) {
@Override
public <Q, A> A accept(Visitor<Q, A> v, Q q) {
return null;
}
};
Label lbl = trapwriter.localID(exit);
trapwriter.addTuple(
"exit_cfg_node", lbl, nd instanceof Program ? toplevelLabel : trapwriter.localID(nd));
locationManager.emitNodeLocation(exit, lbl);
exitNodeCache.put(nd, exit);
}
return exit;
}
/**
* Find the target nodes of a jump by consulting the syntactic context.
*
* @param type the type of the jump
* @param label for labelled `BreakStatement` and `ContinueStatement`, the target label;
* otherwise null
*/
private Object findTarget(final JumpType type, final String label) {
return new Object() {
private Object find(final int i) {
if (i < 0) return null;
Node nd = ctxt.get(i);
if (nd instanceof Finally) {
BlockStatement finalizer = ((Finally) nd).body;
followingCache.put(finalizer, union(followingCache.get(finalizer), find(i - 1)));
return First.of(finalizer);
}
return nd.accept(
new DefaultVisitor<Void, Object>() {
@Override
public Object visit(Loop loop, Void v) {
Set<String> labels = loopLabels.computeIfAbsent(loop, k -> new LinkedHashSet<>());
if (type == JumpType.CONTINUE && (label == null || labels.contains(label)))
return First.of(loop.getContinueTarget());
else if (type == JumpType.BREAK && label == null) return followingCache.get(loop);
return find(i - 1);
}
@Override
public Object visit(SwitchStatement nd, Void v) {
if (type == JumpType.BREAK && label == null) return followingCache.get(nd);
return find(i - 1);
}
@Override
public Object visit(LabeledStatement nd, Void v) {
if (type == JumpType.BREAK && nd.getLabel().getName().equals(label))
return followingCache.get(nd);
return find(i - 1);
}
@Override
public Object visit(TryStatement t, Void v) {
if (type == JumpType.THROW && !t.getAllHandlers().isEmpty()) {
return First.of(t.getAllHandlers().get(0));
}
if (t.hasFinalizer()) {
BlockStatement finalizer = t.getFinalizer();
followingCache.put(
finalizer, union(followingCache.get(finalizer), find(i - 1)));
return First.of(finalizer);
}
return find(i - 1);
}
@Override
public Object visit(Program nd, Void v) {
return visit(nd);
}
@Override
public Object visit(IFunction nd, Void v) {
return visit(nd);
}
private Object visit(IStatementContainer nd) {
if (type == JumpType.RETURN) return exit((IStatementContainer) nd);
return null;
}
},
null);
}
}.find(ctxt.size() - 1);
}
private Node visit(Node nd, Object trueSuccessors, Object falseSuccessors) {
if (nd == null) return null;
followingCache.put(nd, union(followingCache.get(nd), union(trueSuccessors, falseSuccessors)));
nd.accept(
this,
falseSuccessors == null
? new SimpleSuccessorInfo(trueSuccessors)
: new SplitSuccessorInfo(trueSuccessors, falseSuccessors));
return First.of(nd);
}
private Object seq(Object... nodes) {
Object fst = nodes[nodes.length - 1];
for (int i = nodes.length - 2; i >= 0; --i) {
for (Node node : hcaerof(nodes[i])) {
Node ffst = visit(node, fst, null);
if (ffst != null) fst = ffst;
}
}
return fst;
}
@Override
public Void visit(Node nd, SuccessorInfo i) {
succ(nd, i.getAllSuccessors());
return null;
}
@Override
public Void visit(Expression nd, SuccessorInfo i) {
succ(nd, i.getGuardedSuccessors(nd));
return null;
}
@Override
public Void visit(Program nd, SuccessorInfo i) {
this.ctxt.push(nd);
Node entry = this.entry(nd);
List<ImportDeclaration> imports = scanImports(nd);
hoistedImports.addAll(imports);
List<ImportSpecifier> importSpecifiers = new ArrayList<>();
for (ImportDeclaration imp : imports) importSpecifiers.addAll(imp.getSpecifiers());
List<Identifier> fns = HoistedFunDecls.of(nd);
hoistedFns.addAll(fns);
Object fst = this.seq(importSpecifiers, fns, nd.getBody(), this.exit(nd));
succ(entry, fst);
this.ctxt.pop();
return null;
}
/** Return a list of all {@link ImportDeclaration}s in the given program, in lexical order. */
private List<ImportDeclaration> scanImports(Program p) {
List<ImportDeclaration> result = new ArrayList<>();
// import statements can only appear at the top-level
for (Statement s : p.getBody())
if (s instanceof ImportDeclaration) result.add((ImportDeclaration) s);
return result;
}
/**
* Builds the CFG for the creation of the given function as part of CFG the enclosing container.
*/
private void buildFunctionCreation(IFunction nd, SuccessorInfo i) {
// `tail` is the last CFG node in the function creation
INode tail = nd;
if (!(nd instanceof AFunctionExpression) && !hoistedFns.contains(nd.getId())) {
succ(tail, nd.getId());
tail = nd.getId();
}
succ(tail, nd instanceof AFunctionExpression ? i.getSuccessors(true) : i.getAllSuccessors());
}
/** Builds the CFG for the body of the given function. */
private void buildFunctionBody(IFunction nd) {
this.ctxt.push((Node) nd);
// build a list of all parameters and default expressions in order, with
// the default expressions preceding their corresponding parameter
List<Expression> paramsAndDefaults = new ArrayList<Expression>();
for (int j = 0, n = nd.getParams().size(); j < n; ++j) {
if (nd.hasDefault(j)) paramsAndDefaults.add(nd.getDefault(j));
paramsAndDefaults.add((Expression) nd.getParams().get(j));
}
if (nd.hasRest()) paramsAndDefaults.add((Expression) nd.getRest());
Node entry = this.entry(nd);
List<Identifier> fns = HoistedFunDecls.of(nd);
hoistedFns.addAll(fns);
// if this is the constructor of a class without a superclass, we need to
// initialise all fields before running the body of the constructor
// (for classes with a superclass, that initialisation only happens after
// `super` calls)
AClass klass = constructor2Class.get(nd);
FieldDefinition firstField = null;
if (klass != null && !klass.hasSuperClass()) {
Pair<FieldDefinition, FieldDefinition> p = instanceFields.peek();
if (p != null) {
firstField = p.fst();
succ(p.snd(), First.of(nd.getBody()));
}
}
Object fst = this.seq(nd.getBody(), this.exit(nd));
if (firstField != null) fst = First.of(firstField);
fst =
this.seq(
nd instanceof FunctionDeclaration ? null : nd.getId(), paramsAndDefaults, fns, fst);
succ(entry, fst);
this.ctxt.pop();
}
@Override
public Void visit(IFunction nd, SuccessorInfo i) {
// save per-function caches
Map<Statement, Set<String>> oldLoopLabels = loopLabels;
Map<Node, Object> oldFollowingCache = followingCache;
Map<Chainable, SuccessorInfo> oldChainRootSuccessors = chainRootSuccessors;
// clear caches
loopLabels = new LinkedHashMap<>();
followingCache = new LinkedHashMap<>();
chainRootSuccessors = new LinkedHashMap<>();
if (nd instanceof FunctionDeclaration && nd.hasDeclareKeyword()) {
// All 'declared' statements have a no-op CFG node, but their children should
// not be processed.
succ(nd, i.getAllSuccessors());
return null;
}
buildFunctionCreation(nd, i);
buildFunctionBody(nd);
// restore caches
loopLabels = oldLoopLabels;
followingCache = oldFollowingCache;
chainRootSuccessors = oldChainRootSuccessors;
return null;
}
@Override
public Void visit(ClassDeclaration nd, SuccessorInfo i) {
if (nd.hasDeclareKeyword()) {
succ(nd, i.getAllSuccessors());
} else {
visit(nd, nd.getClassDef(), i);
}
return null;
}
@Override
public Void visit(ClassExpression nd, SuccessorInfo i) {
return visit(nd, nd.getClassDef(), i);
}
private Map<Object, AClass> constructor2Class = new LinkedHashMap<>();
private Void visit(Node nd, AClass ac, SuccessorInfo i) {
for (MemberDefinition<?> m : ac.getBody().getBody())
if (m.isConstructor() && m.isConcrete()) constructor2Class.put(m.getValue(), ac);
seq(ac.getId(), ac.getSuperClass(), ac.getBody(), nd);
succ(nd, seq(getStaticFields(ac.getBody()), getDecoratorsOfClass(ac), i.getAllSuccessors()));
return null;
}
/**
* Gets the decorators for the given member, including parameter decorators.
*
* <p>The result is a tree of nested lists containing Decorator and DecoratorList nodes at the
* leaves.
*/
private List<?> getMemberDecorators(MemberDefinition<?> member) {
if (member instanceof MethodDefinition) {
MethodDefinition method = (MethodDefinition) member;
return Arrays.asList(method.getValue().getParameterDecorators(), method.getDecorators());
} else {
return member.getDecorators();
}
}
/**
* Returns all the decorators on the given class and its members in the order the decorators are
* evaluated.
*
* <p>We don't model the call to each decorator, only the initial evaluation.
*
* <p>The result is a list of Decorator and DecoratorList nodes.
*/
private List<Node> getDecoratorsOfClass(AClass ac) {
List<Object> instanceDecorators = new ArrayList<>();
List<Object> staticDecorators = new ArrayList<>();
List<Object> constructorParameterDecorators = new ArrayList<>();
List<?> classDecorators = ac.getDecorators();
for (MemberDefinition<?> member : ac.getBody().getBody()) {
if (!member.isConcrete()) continue;
List<?> decorators = getMemberDecorators(member);
if (member.isConstructor()) {
constructorParameterDecorators.add(decorators);
} else if (member.isStatic()) {
staticDecorators.add(decorators);
} else {
instanceDecorators.add(decorators);
}
}
return flattenNestedList(
Arrays.asList(
instanceDecorators,
staticDecorators,
constructorParameterDecorators,
classDecorators));
}
@Override
public Void visit(NamespaceDeclaration nd, SuccessorInfo i) {
if (nd.hasDeclareKeyword()) {
succ(nd, i.getAllSuccessors());
} else {
List<Identifier> hoisted = HoistedFunDecls.of(nd.getBody());
hoistedFns.addAll(hoisted);
succ(nd.getName(), nd);
succ(nd, seq(hoisted, nd.getBody(), i.getAllSuccessors()));
}
return null;
}
@Override
public Void visit(Literal nd, SuccessorInfo i) {
if (nd.isFalsy()) {
succ(nd, i.getSuccessors(false));
} else {
succ(nd, i.getSuccessors(true));
}
return null;
}
@Override
public Void visit(BlockStatement nd, SuccessorInfo i) {
if (nd.getBody().isEmpty()) succ(nd, i.getAllSuccessors());
else succ(nd, First.of(nd.getBody().get(0)));
seq(nd.getBody(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(CatchClause nd, SuccessorInfo i) {
// check whether this is a guarded catch
if (nd.hasGuard()) {
// if so, the guard may fail and execution might continue with the next
// catch clause (if any)
succ(nd, nd.getParam());
this.seq(
nd.getParam(), nd.getGuard(), union(First.of(nd.getBody()), i.getSuccessors(false)));
this.seq(nd.getBody(), i.getSuccessors(true));
} else {
// unguarded catch clauses always execute their body
if (nd.getParam() != null) {
succ(nd, nd.getParam());
this.seq(nd.getParam(), nd.getBody(), i.getAllSuccessors());
} else {
succ(nd, First.of(nd.getBody()));
this.seq(nd.getBody(), i.getAllSuccessors());
}
}
return null;
}
@Override
public Void visit(LabeledStatement nd, SuccessorInfo i) {
Set<String> ndLabels = loopLabels.computeIfAbsent(nd, k -> new LinkedHashSet<>()),
bodyLabels = loopLabels.computeIfAbsent(nd.getBody(), k -> new LinkedHashSet<>());
bodyLabels.addAll(ndLabels);
bodyLabels.add(nd.getLabel().getName());
succ(nd, First.of(nd.getBody()));
this.ctxt.push(nd);
this.seq(nd.getBody(), i.getAllSuccessors());
this.ctxt.pop();
return null;
}
@Override
public Void visit(ExpressionStatement nd, SuccessorInfo i) {
succ(nd, First.of(nd.getExpression()));
visit(nd.getExpression(), i.getAllSuccessors(), null);
return null;
}
@Override
public Void visit(ParenthesizedExpression nd, SuccessorInfo i) {
succ(nd, First.of(nd.getExpression()));
return nd.getExpression().accept(this, i);
}
@Override
public Void visit(IfStatement nd, SuccessorInfo i) {
Expression test = nd.getTest();
succ(nd, First.of(test));
Object following = i.getAllSuccessors();
visit(
test,
First.of(nd.getConsequent()),
nd.hasAlternate() ? First.of(nd.getAlternate()) : following);
this.visit(nd.getConsequent(), following, null);
this.visit(nd.getAlternate(), following, null);
return null;
}
@Override
public Void visit(ConditionalExpression nd, SuccessorInfo i) {
Expression test = nd.getTest();
succ(nd, First.of(test));
visit(test, First.of(nd.getConsequent()), First.of(nd.getAlternate()));
nd.getConsequent().accept(this, i);
nd.getAlternate().accept(this, i);
return null;
}
@Override
public Void visit(JumpStatement nd, SuccessorInfo i) {
JumpType tp = nd instanceof BreakStatement ? JumpType.BREAK : JumpType.CONTINUE;
succ(nd, findTarget(tp, nd.hasLabel() ? nd.getLabel().getName() : null));
return null;
}
@Override
public Void visit(WithStatement nd, SuccessorInfo i) {
succ(nd, First.of(nd.getObject()));
seq(nd.getObject(), nd.getBody(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(SwitchStatement nd, SuccessorInfo i) {
this.ctxt.push(nd);
succ(nd, First.of(nd.getDiscriminant()));
// find all default cases (in a valid program there is
// only one, but we want to gracefully handle switches with
// multiple defaults)
Object deflt = null;
for (SwitchCase c : nd.getCases()) if (c.isDefault()) deflt = union(deflt, c);
// compute 'following' for every case label
outer:
for (int j = 0, n = nd.getCases().size(); j < n; ++j) {
SwitchCase cse = nd.getCases().get(j);
if (cse.hasTest()) {
// find next non-default clause
for (int k = j + 1; k < n; ++k) {
if (nd.getCases().get(k).hasTest()) {
followingCache.put(cse.getTest(), nd.getCases().get(k));
continue outer;
}
}
// if there isn't one, the default clause is next
if (deflt != null) followingCache.put(cse.getTest(), deflt);
else
// if there is no default clause, execution continues after the `switch`
followingCache.put(cse.getTest(), i.getAllSuccessors());
}
}
if (nd.getCases().isEmpty()) this.visit(nd.getDiscriminant(), i.getAllSuccessors(), null);
else if (nd.getCases().size() > 1 && nd.getCases().get(0).isDefault())
this.visit(nd.getDiscriminant(), First.of(nd.getCases().get(1)), null);
else this.visit(nd.getDiscriminant(), First.of(nd.getCases().get(0)), null);
this.seq(nd.getCases(), i.getAllSuccessors());
this.ctxt.pop();
return null;
}
@Override
public Void visit(SwitchCase nd, SuccessorInfo i) {
if (nd.hasTest()) succ(nd, First.of(nd.getTest()));
else if (!nd.getConsequent().isEmpty()) succ(nd, First.of(nd.getConsequent().get(0)));
else succ(nd, followingCache.get(nd));
Object fst = followingCache.get(nd.getTest());
if (nd.getConsequent().isEmpty()) fst = union(i.getAllSuccessors(), fst);
else fst = union(First.of(nd.getConsequent().get(0)), fst);
seq(nd.getTest(), fst);
seq(nd.getConsequent(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(ReturnStatement nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
succ(nd, findTarget(JumpType.RETURN, null));
return null;
}
@Override
public Void visit(ThrowStatement nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
succ(nd, findTarget(JumpType.THROW, null));
return null;
}
@Override
public Void visit(TryStatement nd, SuccessorInfo i) {
succ(nd, First.of(nd.getBlock()));
if (nd.hasFinalizer()) followingCache.put(nd.getFinalizer(), i.getAllSuccessors());
ctxt.push(nd);
Object fst = nd.hasFinalizer() ? First.of(nd.getFinalizer()) : i.getAllSuccessors();
this.visit(nd.getBlock(), fst, null);
ctxt.pop();
if (nd.hasFinalizer()) ctxt.push(new Finally(nd.getFinalizer().getLoc(), nd.getFinalizer()));
for (int j = 0, n = nd.getAllHandlers().size(); j < n; ++j)
visit(nd.getAllHandlers().get(j), fst, j + 1 < n ? nd.getAllHandlers().get(j + 1) : null);
if (nd.hasFinalizer()) {
ctxt.pop();
visit(nd.getFinalizer(), followingCache.get(nd.getFinalizer()), null);
}
return null;
}
@Override
public Void visit(VariableDeclaration nd, SuccessorInfo i) {
if (nd.hasDeclareKeyword()) {
succ(nd, i.getAllSuccessors());
} else {
succ(nd, First.of(nd.getDeclarations().get(0)));
seq(nd.getDeclarations(), i.getAllSuccessors());
}
return null;
}
@Override
public Void visit(ImportWholeDeclaration nd, SuccessorInfo i) {
seq(nd.getLhs(), nd.getRhs(), nd);
succ(nd, i.getAllSuccessors());
return null;
}
@Override
public Void visit(ExportWholeDeclaration nd, SuccessorInfo i) {
succ(nd, First.of(nd.getRhs()));
seq(nd.getRhs(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(LetStatement nd, SuccessorInfo i) {
succ(nd, First.of(nd.getHead().get(0)));
seq(nd.getHead(), nd.getBody(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(LetExpression nd, SuccessorInfo i) {
succ(nd, First.of(nd.getHead().get(0)));
seq(nd.getHead(), nd.getBody(), i.getGuardedSuccessors(nd));
return null;
}
@Override
public Void visit(WhileStatement nd, SuccessorInfo i) {
Expression test = nd.getTest();
Node testStart = First.of(test);
succ(nd, testStart);
ctxt.push(nd);
visit(nd.getBody(), testStart, null);
visit(test, First.of(nd.getBody()), i.getAllSuccessors());
ctxt.pop();
return null;
}
@Override
public Void visit(DoWhileStatement nd, SuccessorInfo i) {
Node body = First.of(nd.getBody());
succ(nd, body);
ctxt.push(nd);
Expression test = nd.getTest();
visit(nd.getBody(), First.of(test), null);
visit(test, body, i.getAllSuccessors());
ctxt.pop();
return null;
}
@Override
public Void visit(EnhancedForStatement nd, SuccessorInfo i) {
seq(nd.getRight(), nd);
succ(nd, First.of(nd.getLeft()));
succ(nd, i.getAllSuccessors());
ctxt.push(nd);
seq(nd.getLeft(), nd.getDefaultValue(), nd.getBody(), nd);
ctxt.pop();
return null;
}
@Override
public Void visit(ForStatement nd, SuccessorInfo i) {
succ(nd, First.of(nd.hasInit() ? nd.getInit() : nd.hasTest() ? nd.getTest() : nd.getBody()));
ctxt.push(nd);
Node fst = First.of(nd.hasTest() ? nd.getTest() : nd.getBody());
visit(nd.getInit(), fst, null);
if (nd.hasTest()) {
Expression test = nd.getTest();
visit(test, First.of(nd.getBody()), i.getAllSuccessors());
}
seq(nd.getBody(), nd.getUpdate(), fst);
ctxt.pop();
return null;
}
@Override
public Void visit(SequenceExpression nd, SuccessorInfo i) {
List<Expression> expressions = nd.getExpressions();
succ(nd, First.of(expressions.get(0)));
int n = expressions.size() - 1;
expressions.get(n).accept(this, i);
Node next = First.of(expressions.get(n));
while (--n >= 0) next = visit(expressions.get(n), next, null);
return null;
}
@Override
public Void visit(ArrayExpression nd, SuccessorInfo i) {
visitArrayLike(nd, nd.getElements(), i.getAllSuccessors());
return null;
}
@Override
public Void visit(ArrayPattern nd, SuccessorInfo i) {
// build a list of all pattern elements and default expressions in order, with
// the default expressions preceding their corresponding elements
List<Expression> elementsAndDefaults = new ArrayList<Expression>();
List<Expression> elements = nd.getElements();
List<Expression> defaults = nd.getDefaults();
for (int j = 0, n = elements.size(); j < n; ++j) {
elementsAndDefaults.add(defaults.get(j));
elementsAndDefaults.add(elements.get(j));
}
if (nd.hasRest()) elementsAndDefaults.add(nd.getRest());
visitArrayLike(nd, elementsAndDefaults, i.getAllSuccessors());
return null;
}
public void visitArrayLike(Node nd, List<? extends INode> elements, Object following) {
// find the first non-omitted element
boolean foundNonOmitted = false;
for (INode element : elements)
if (element != null) {
// `nd` is followed by the first non-omitted element
foundNonOmitted = true;
succ(nd, First.of((Node) element));
break;
}
// if all elements are omitted, `nd` is immediately followed by `following`
if (!foundNonOmitted) succ(nd, following);
seq(elements, following);
}
@Override
public Void visit(ObjectExpression nd, SuccessorInfo i) {
visitObjectLike(nd, nd.getProperties(), i);
return null;
}
@Override
public Void visit(ObjectPattern nd, SuccessorInfo i) {
List<Node> allProperties = new ArrayList<Node>();
allProperties.addAll(nd.getProperties());
if (nd.hasRest()) allProperties.add(nd.getRest());
visitObjectLike(nd, allProperties, i);
return null;
}
/** For each enclosing class, this records the first and last non-abstract instance fields. */
private Stack<Pair<FieldDefinition, FieldDefinition>> instanceFields = new Stack<>();
@Override
public Void visit(ClassBody nd, SuccessorInfo i) {
List<FieldDefinition> fds = getConcreteInstanceFields(nd);
if (fds.isEmpty()) {
instanceFields.push(null);
} else {
seq(fds, null);
instanceFields.push(Pair.make(fds.get(0), fds.get(fds.size() - 1)));
}
seq(getMethods(nd), i.getAllSuccessors());
instanceFields.pop();
return null;
}
private List<MemberDefinition<?>> getMethods(ClassBody nd) {
List<MemberDefinition<?>> mds = new ArrayList<>();
for (MemberDefinition<?> md : nd.getBody()) {
if (md instanceof MethodDefinition) mds.add(md);
}
return mds;
}
private List<MemberDefinition<?>> getStaticFields(ClassBody nd) {
List<MemberDefinition<?>> mds = new ArrayList<>();
for (MemberDefinition<?> md : nd.getBody()) {
if (md instanceof FieldDefinition && md.isStatic()) mds.add(md);
}
return mds;
}
private List<FieldDefinition> getConcreteInstanceFields(ClassBody nd) {
List<FieldDefinition> fds = new ArrayList<>();
for (MemberDefinition<?> md : nd.getBody())
if (md instanceof FieldDefinition && !md.isStatic() && md.isConcrete())
fds.add((FieldDefinition) md);
return fds;
}
public Void visitObjectLike(Node nd, List<? extends Node> properties, SuccessorInfo i) {
if (properties.isEmpty()) succ(nd, i.getAllSuccessors());
else succ(nd, First.of(properties.get(0)));
seq(properties, i.getAllSuccessors());
return null;
}
@Override
public Void visit(Property nd, SuccessorInfo i) {
this.seq(nd.getKey(), nd.getValue(), nd.getDefaultValue(), nd.getDecorators(), nd);
succ(nd, i.getAllSuccessors());
return null;
}
@Override
public Void visit(MemberDefinition<?> nd, SuccessorInfo i) {
if (nd.isConcrete() && !nd.isParameterField()) {
this.seq(nd.getKey(), nd.getValue(), nd);
}
succ(nd, i.getAllSuccessors());
return null;
}
@Override
public Void visit(AssignmentExpression nd, SuccessorInfo i) {
visitAssign(nd, nd.getLeft(), nd.getRight());
succ(nd, i.getGuardedSuccessors(nd));
return null;
}
protected void visitAssign(INode assgn, INode lhs, Expression rhs) {
if (lhs instanceof DestructuringPattern) seq(rhs, lhs, assgn);
else seq(lhs, rhs, assgn);
}
@Override
public Void visit(BinaryExpression nd, SuccessorInfo i) {
if ("??".equals(nd.getOperator())) {
// the nullish coalescing operator is short-circuiting, but we do not add guards for it
succ(nd, First.of(nd.getLeft()));
Object leftSucc =
union(
First.of(nd.getRight()),
i.getAllSuccessors()); // short-circuiting happens with both truthy and falsy values
visit(nd.getLeft(), leftSucc, null);
nd.getRight().accept(this, i);
} else {
this.seq(nd.getLeft(), nd.getRight(), nd);
succ(nd, i.getGuardedSuccessors(nd));
}
return null;
}
@Override
public Void visit(VariableDeclarator nd, SuccessorInfo i) {
visitAssign(nd, nd.getId(), nd.getInit());
succ(nd, i.getAllSuccessors());
return null;
}
// special treatment of short-circuiting operators as explained above
@Override
public Void visit(LogicalExpression nd, SuccessorInfo i) {
Expression left = nd.getLeft();
succ(nd, First.of(left));
if ("&&".equals(nd.getOperator()))
visit(left, First.of(nd.getRight()), i.getSuccessors(false));
else visit(left, i.getSuccessors(true), First.of(nd.getRight()));
nd.getRight().accept(this, i);
return null;
}
@Override
public Void visit(SpreadElement nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
succ(nd, i.getAllSuccessors());
return null;
}
@Override
public Void visit(UnaryExpression nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
succ(nd, i.getGuardedSuccessors(nd));
return null;
}
@Override
public Void visit(UpdateExpression nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
succ(nd, i.getGuardedSuccessors(nd));
return null;
}
@Override
public Void visit(YieldExpression nd, SuccessorInfo i) {
visit(nd.getArgument(), nd, null);
// yield expressions may throw
succ(nd, union(this.findTarget(JumpType.THROW, null), i.getGuardedSuccessors(nd)));
return null;
}
private void preVisitChainable(Chainable chainable, Expression base, SuccessorInfo i) {
if (!chainable
.isOnOptionalChain()) // optimization: bookkeeping is only needed for optional chains
return;
// start of chain
chainRootSuccessors.putIfAbsent(chainable, i);
// next step in chain
if (base instanceof Chainable)
chainRootSuccessors.put((Chainable) base, chainRootSuccessors.get(chainable));
}
private void postVisitChainable(Chainable chainable, Expression base, boolean optional) {
if (optional) {
succ(base, chainRootSuccessors.get(chainable).getSuccessors(false));
}
chainRootSuccessors.remove(chainable);
}
@Override
public Void visit(MemberExpression nd, SuccessorInfo i) {
preVisitChainable(nd, nd.getObject(), i);
seq(nd.getObject(), nd.getProperty(), nd);
// property accesses may throw
succ(nd, union(this.findTarget(JumpType.THROW, null), i.getGuardedSuccessors(nd)));
postVisitChainable(nd, nd.getObject(), nd.isOptional());
return null;
}
@Override
public Void visit(InvokeExpression nd, SuccessorInfo i) {
preVisitChainable(nd, nd.getCallee(), i);
seq(nd.getCallee(), nd.getArguments(), nd);
Object succs = i.getGuardedSuccessors(nd);
if (nd instanceof CallExpression
&& nd.getCallee() instanceof Super
&& !instanceFields.isEmpty()) {
Pair<FieldDefinition, FieldDefinition> p = instanceFields.peek();
if (p != null) {
FieldDefinition firstField = p.fst();
FieldDefinition lastField = p.snd();
succ(lastField, succs);
succs = First.of(firstField);
}
}
// calls may throw
succ(nd, union(this.findTarget(JumpType.THROW, null), succs));
postVisitChainable(nd, nd.getCallee(), nd.isOptional());
return null;
}
@Override
public Void visit(TaggedTemplateExpression nd, SuccessorInfo i) {
succ(nd, First.of(nd.getTag()));
seq(nd.getTag(), nd.getQuasi(), i.getGuardedSuccessors(nd));
return null;
}
@Override
public Void visit(TemplateLiteral nd, SuccessorInfo i) {
if (nd.getChildren().isEmpty()) {
succ(nd, i.getSuccessors(false));
} else {
succ(nd, First.of(nd.getChildren().get(0)));
seq(nd.getChildren(), i.getGuardedSuccessors(nd));
}
return null;
}
@Override
public Void visit(ComprehensionExpression nd, SuccessorInfo i) {
succ(nd, visitComprehensionBlock(nd, 0, i.getSuccessors(true)));
return null;
}
private Node visitComprehensionBlock(ComprehensionExpression nd, int i, Object follow) {
int n = nd.getBlocks().size();
if (i >= n) {
return visitComprehensionFilter(nd, follow);
} else {
ComprehensionBlock block = nd.getBlocks().get(i);
succ(block, First.of(block.getRight()));
follow = union(First.of((Node) block.getLeft()), follow);
seq(block.getRight(), follow);
seq(block.getLeft(), visitComprehensionBlock(nd, i + 1, follow));
return First.of(block);
}
}
private Node visitComprehensionFilter(ComprehensionExpression nd, Object follow) {
if (nd.hasFilter()) {
visit(nd.getFilter(), visitComprehensionBody(nd, follow), follow);
return First.of(nd.getFilter());
} else {
return visitComprehensionBody(nd, follow);
}
}
private Node visitComprehensionBody(ComprehensionExpression nd, Object back) {
seq(nd.getBody(), back);
return First.of(nd.getBody());
}
@Override
public Void visit(ExportAllDeclaration nd, SuccessorInfo c) {
succ(nd, First.of(nd.getSource()));
seq(nd.getSource(), c.getAllSuccessors());
return null;
}
@Override
public Void visit(ExportDefaultDeclaration nd, SuccessorInfo c) {
succ(nd, First.of(nd.getDeclaration()));
seq(nd.getDeclaration(), c.getAllSuccessors());
return null;
}
@Override
public Void visit(ExportNamedDeclaration nd, SuccessorInfo c) {
if (nd.hasDeclaration()) {
succ(nd, First.of(nd.getDeclaration()));
seq(nd.getDeclaration(), c.getAllSuccessors());
} else if (nd.hasSource()) {
succ(nd, First.of(nd.getSource()));
seq(nd.getSource(), nd.getSpecifiers(), c.getAllSuccessors());
} else if (nd.getSpecifiers().isEmpty()) {
succ(nd, c.getAllSuccessors());
} else {
succ(nd, First.of(nd.getSpecifiers().get(0)));
seq(nd.getSpecifiers(), c.getAllSuccessors());
}
return null;
}
@Override
public Void visit(ExportSpecifier nd, SuccessorInfo c) {
succ(nd, First.of(nd.getLocal()));
seq(nd.getLocal(), nd.getExported(), c.getAllSuccessors());
return null;
}
@Override
public Void visit(ExportDefaultSpecifier nd, SuccessorInfo c) {
succ(nd, First.of(nd.getExported()));
seq(nd.getExported(), c.getAllSuccessors());
return null;
}
@Override
public Void visit(ExportNamespaceSpecifier nd, SuccessorInfo c) {
succ(nd, First.of(nd.getExported()));
seq(nd.getExported(), c.getAllSuccessors());
return null;
}
@Override
public Void visit(ImportDeclaration nd, SuccessorInfo c) {
if (hoistedImports.contains(nd) || nd.getSpecifiers().isEmpty()) {
succ(nd, c.getAllSuccessors());
} else {
succ(nd, First.of(nd.getSpecifiers().get(0)));
seq(nd.getSpecifiers(), c.getAllSuccessors());
}
return null;
}
@Override
public Void visit(ImportSpecifier nd, SuccessorInfo c) {
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(JSXElement nd, SuccessorInfo c) {
JSXOpeningElement open = nd.getOpeningElement();
IJSXName name = open.getName();
if (name == null) seq(nd.getChildren(), nd);
else seq(name, open.getAttributes(), nd.getChildren(), nd);
succ(nd, c.getSuccessors(true));
return null;
}
@Override
public Void visit(JSXMemberExpression nd, SuccessorInfo c) {
seq(nd.getObject(), nd.getName(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(JSXNamespacedName nd, SuccessorInfo c) {
seq(nd.getNamespace(), nd.getName(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(JSXAttribute nd, SuccessorInfo c) {
seq(nd.getName(), nd.getValue(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(JSXSpreadAttribute nd, SuccessorInfo c) {
visit(nd.getArgument(), nd, null);
Label propkey = trapwriter.localID(nd, "JSXSpreadAttribute");
Label spreadkey = trapwriter.localID(nd);
trapwriter.addTuple("successor", spreadkey, propkey);
for (Node succ : foreach(c.getAllSuccessors())) succ(propkey, succ);
return null;
}
@Override
public Void visit(JSXExpressionContainer nd, SuccessorInfo c) {
return nd.getExpression().accept(this, c);
}
@Override
public Void visit(AwaitExpression nd, SuccessorInfo c) {
seq(nd.getArgument(), nd);
// `await` may throw
succ(nd, union(this.findTarget(JumpType.THROW, null), c.getGuardedSuccessors(nd)));
return null;
}
@Override
public Void visit(Decorator nd, SuccessorInfo c) {
seq(nd.getExpression(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(BindExpression nd, SuccessorInfo c) {
seq(nd.getObject(), nd.getCallee(), nd);
succ(nd, c.getSuccessors(true));
return null;
}
@Override
public Void visit(ExternalModuleReference nd, SuccessorInfo c) {
seq(nd.getExpression(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(DynamicImport nd, SuccessorInfo c) {
seq(nd.getSource(), nd);
succ(nd, c.getSuccessors(true));
return null;
}
@Override
public Void visit(ExpressionWithTypeArguments nd, SuccessorInfo c) {
seq(nd.getExpression(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(TypeAssertion nd, SuccessorInfo c) {
seq(nd.getExpression(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(NonNullAssertion nd, SuccessorInfo c) {
seq(nd.getExpression(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(EnumDeclaration nd, SuccessorInfo c) {
seq(nd.getId(), nd.getMembers(), nd.getDecorators(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(EnumMember nd, SuccessorInfo c) {
seq(nd.getId(), nd.getInitializer(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(DecoratorList nd, SuccessorInfo c) {
seq(nd.getDecorators(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(XMLAnyName nd, SuccessorInfo c) {
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(XMLAttributeSelector nd, SuccessorInfo c) {
seq(nd.getAttribute(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(XMLFilterExpression nd, SuccessorInfo c) {
seq(nd.getLeft(), nd.getRight(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(XMLQualifiedIdentifier nd, SuccessorInfo c) {
seq(nd.getLeft(), nd.getRight(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
@Override
public Void visit(XMLDotDotExpression nd, SuccessorInfo c) {
seq(nd.getLeft(), nd.getRight(), nd);
succ(nd, c.getAllSuccessors());
return null;
}
}
public void extract(Node nd) {
metrics.startPhase(ExtractionPhase.CFGExtractor_extract);
nd.accept(new V(), new SimpleSuccessorInfo(null));
metrics.stopPhase(ExtractionPhase.CFGExtractor_extract);
}
}
| 67,647 | 33.408952 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/ExtractorConfig.java | package com.semmle.js.extractor;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import com.semmle.js.parser.JcornWrapper;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.UserError;
/**
* Configuration options that affect the behaviour of the extractor.
*
* <p>The intended invariants are:
*
* <ol>
* <li>If the extractor is invoked twice on the same file (contents and path both the same) with
* the same configuration options, it will produce exactly the same TRAP files.
* <li>If the extractor is invoked on two files that have the same content, but whose path (and
* file extension) may be different, and the two invocations have the same configuration
* options, then the trap files it produces are identical from label #20000 onwards. (See
* comments on the trap cache below for further explanation.)
* </ol>
*/
public class ExtractorConfig {
public static enum ECMAVersion {
ECMA3(3),
ECMA5(5),
ECMA2015(2015, 6),
ECMA2016(2016, 7),
ECMA2017(2017, 8),
ECMA2018(2018, 9),
ECMA2019(2019, 10),
ECMA2020(2020, 11);
private final int version;
public final int legacyVersion;
private ECMAVersion(int version, int legacyVersion) {
this.version = version;
this.legacyVersion = legacyVersion;
}
private ECMAVersion(int version) {
this(version, version);
}
public static ECMAVersion of(int version) {
for (ECMAVersion v : values())
if (v.version == version || v.legacyVersion == version) return v;
return null;
}
};
/**
* The type of a source file, which together with the {@link Platform} determines how the
* top-level scope of the file behaves, and whether ES2015 module syntax should be allowed.
*
* <p>Note that the names of these enum members are depended on by {@link Main}, {@link
* AutoBuild}, and {@link JcornWrapper}.
*/
public static enum SourceType {
/** A script executed in the global scope. */
SCRIPT,
/** An ES2015 module. */
MODULE,
/** A Closure-Library module, defined using `goog.module()`. */
CLOSURE_MODULE,
/** A CommonJS module that is not also an ES2015 module. */
COMMONJS_MODULE,
/** Automatically determined source type. */
AUTO;
@Override
public String toString() {
return StringUtil.lc(name());
}
/**
* Returns true if this source is executed directly in the global scope, or false if it has its
* own local scope.
*/
public boolean hasLocalScope() {
return this != SCRIPT;
}
/** Returns true if this source is implicitly in strict mode. */
public boolean isStrictMode() {
return this == MODULE;
}
private static final Set<String> closureLocals = Collections.singleton("exports");
private static final Set<String> commonJsLocals =
new LinkedHashSet<>(
Arrays.asList("require", "module", "exports", "__filename", "__dirname", "arguments"));
/**
* Returns the set of local variables in scope at the top-level of this module.
*
* <p>If this source type has no local scope, the empty set is returned.
*/
public Set<String> getPredefinedLocals(Platform platform, String extension) {
switch (this) {
case CLOSURE_MODULE:
return closureLocals;
case COMMONJS_MODULE:
return commonJsLocals;
case MODULE:
if (platform == Platform.NODE && !extension.equals(".mjs")) {
// An ES2015 module that is compiled to a Node.js module effectively has the locals
// from Node.js even if they are not part of the ES2015 standard.
return commonJsLocals;
}
return Collections.emptySet();
default:
return Collections.emptySet();
}
}
};
public static enum Platform {
WEB,
NODE,
AUTO;
@Override
public String toString() {
return StringUtil.lc(name());
}
private static final Set<String> nodejsGlobals =
new LinkedHashSet<>(Arrays.asList("global", "process", "console", "Buffer"));
/** Gets the set of predefined globals for this platform. */
public Set<String> getPredefinedGlobals() {
return this == NODE ? nodejsGlobals : Collections.emptySet();
}
}
/** How to handle HTML files. */
public static enum HTMLHandling {
/** Only extract embedded scripts, not the HTML itself. */
SCRIPTS(false, false),
/** Only extract elements and embedded scripts, not text. */
ELEMENTS(true, false),
/** Extract elements, embedded scripts, and text. */
ALL(true, true);
private final boolean extractElements;
private final boolean extractText;
private HTMLHandling(boolean extractElements, boolean extractText) {
this.extractElements = extractElements;
this.extractText = extractText;
}
public boolean extractElements() {
return extractElements;
}
public boolean extractText() {
return extractText;
}
public boolean extractComments() {
return extractElements;
}
@Override
public String toString() {
return StringUtil.lc(name());
}
}
/** Which language version is the source code parsed as? */
private ECMAVersion ecmaVersion;
/** Is this code parsed as externs definitions? */
private boolean externs;
/** Which {@link Platform} is this code meant to be running on? */
private Platform platform;
/** Should Mozilla-specific language extensions be supported? */
private boolean mozExtensions;
/** Should JScript language extensions be supported? */
private boolean jscript;
/** Should JSX be supported? */
private boolean jsx;
/** Should unfinished ECMAScript proposals be supported? */
private boolean esnext;
/** Should v8-specific language extensions be supported? */
private boolean v8Extensions;
/** Should E4X syntax be supported? */
private boolean e4x;
/** Should parse errors be reported as violations instead of aborting extraction? */
private boolean tolerateParseErrors;
/** How should HTML files be extracted? */
private HTMLHandling htmlHandling;
/**
* Which {@link FileExtractor.FileType} should this code be parsed as?
*
* <p>If this is {@code null}, the file type is inferred from the file extension.
*/
private String fileType;
/** Which {@link SourceType} should this code be parsed as? */
private SourceType sourceType;
/** Should textual information be extracted into the lines/4 relation? */
private boolean extractLines;
/** Should TypeScript files be extracted? */
private TypeScriptMode typescriptMode;
/** Override amount of RAM to allocate to the TypeScript compiler. */
private int typescriptRam;
/** The default character encoding to use for parsing source files. */
private String defaultEncoding;
private VirtualSourceRoot virtualSourceRoot;
public ExtractorConfig(boolean experimental) {
this.ecmaVersion = experimental ? ECMAVersion.ECMA2020 : ECMAVersion.ECMA2019;
this.platform = Platform.AUTO;
this.jsx = true;
this.sourceType = SourceType.AUTO;
this.htmlHandling = HTMLHandling.ELEMENTS;
this.tolerateParseErrors = true;
if (experimental) {
this.mozExtensions = true;
this.jscript = true;
this.esnext = true;
this.v8Extensions = true;
}
this.typescriptMode = TypeScriptMode.NONE;
this.e4x = experimental;
this.defaultEncoding = StandardCharsets.UTF_8.name();
this.virtualSourceRoot = VirtualSourceRoot.none;
}
public ExtractorConfig(ExtractorConfig that) {
this.ecmaVersion = that.ecmaVersion;
this.externs = that.externs;
this.platform = that.platform;
this.mozExtensions = that.mozExtensions;
this.jscript = that.jscript;
this.jsx = that.jsx;
this.esnext = that.esnext;
this.v8Extensions = that.v8Extensions;
this.e4x = that.e4x;
this.tolerateParseErrors = that.tolerateParseErrors;
this.fileType = that.fileType;
this.sourceType = that.sourceType;
this.htmlHandling = that.htmlHandling;
this.extractLines = that.extractLines;
this.typescriptMode = that.typescriptMode;
this.typescriptRam = that.typescriptRam;
this.defaultEncoding = that.defaultEncoding;
this.virtualSourceRoot = that.virtualSourceRoot;
}
public ECMAVersion getEcmaVersion() {
return ecmaVersion;
}
public ExtractorConfig withEcmaVersion(ECMAVersion ecmaVersion) {
ExtractorConfig res = new ExtractorConfig(this);
res.ecmaVersion = ecmaVersion;
return res;
}
public boolean isExterns() {
return externs;
}
public ExtractorConfig withExterns(boolean externs) {
ExtractorConfig res = new ExtractorConfig(this);
res.externs = externs;
return res;
}
public Platform getPlatform() {
return platform;
}
public ExtractorConfig withPlatform(Platform platform) {
ExtractorConfig res = new ExtractorConfig(this);
res.platform = platform;
return res;
}
public boolean isJscript() {
return jscript;
}
public ExtractorConfig withJscript(boolean jscript) {
ExtractorConfig res = new ExtractorConfig(this);
res.jscript = jscript;
return res;
}
public boolean isMozExtensions() {
return mozExtensions;
}
public ExtractorConfig withMozExtensions(boolean mozExtensions) {
ExtractorConfig res = new ExtractorConfig(this);
res.mozExtensions = mozExtensions;
return res;
}
public boolean isEsnext() {
return esnext;
}
public ExtractorConfig withEsnext(boolean esnext) {
ExtractorConfig res = new ExtractorConfig(this);
res.esnext = esnext;
return res;
}
public boolean isV8Extensions() {
return v8Extensions;
}
public ExtractorConfig withV8Extensions(boolean v8Extensions) {
ExtractorConfig res = new ExtractorConfig(this);
res.v8Extensions = v8Extensions;
return res;
}
public boolean isE4X() {
return e4x;
}
public ExtractorConfig withE4X(boolean e4x) {
ExtractorConfig res = new ExtractorConfig(this);
res.e4x = e4x;
return res;
}
public boolean isTolerateParseErrors() {
return tolerateParseErrors;
}
public ExtractorConfig withTolerateParseErrors(boolean tolerateParseErrors) {
ExtractorConfig res = new ExtractorConfig(this);
res.tolerateParseErrors = tolerateParseErrors;
return res;
}
public boolean hasFileType() {
return fileType != null;
}
public String getFileType() {
return fileType;
}
public ExtractorConfig withFileType(String fileType) {
ExtractorConfig res = new ExtractorConfig(this);
res.fileType = fileType;
return res;
}
public SourceType getSourceType() {
return sourceType;
}
public ExtractorConfig withSourceType(SourceType sourceType) {
ExtractorConfig res = new ExtractorConfig(this);
res.sourceType = sourceType;
return res;
}
public boolean isJsx() {
return jsx;
}
public ExtractorConfig withJsx(boolean jsx) {
ExtractorConfig res = new ExtractorConfig(this);
res.jsx = jsx;
return res;
}
public HTMLHandling getHtmlHandling() {
return htmlHandling;
}
public ExtractorConfig withHtmlHandling(HTMLHandling htmlHandling) {
ExtractorConfig res = new ExtractorConfig(this);
res.htmlHandling = htmlHandling;
return res;
}
public boolean getExtractLines() {
return extractLines;
}
public ExtractorConfig withExtractLines(boolean extractLines) {
ExtractorConfig res = new ExtractorConfig(this);
res.extractLines = extractLines;
return res;
}
public TypeScriptMode getTypeScriptMode() {
return typescriptMode;
}
public int getTypeScriptRam() {
return typescriptRam;
}
public ExtractorConfig withTypeScriptMode(TypeScriptMode typescriptMode) {
ExtractorConfig res = new ExtractorConfig(this);
res.typescriptMode = typescriptMode;
return res;
}
public ExtractorConfig withTypeScriptRam(int ram) {
ExtractorConfig res = new ExtractorConfig(this);
res.typescriptRam = ram;
return res;
}
public String getDefaultEncoding() {
return defaultEncoding;
}
public ExtractorConfig withDefaultEncoding(String defaultEncoding) {
ExtractorConfig res = new ExtractorConfig(this);
try {
res.defaultEncoding = Charset.forName(defaultEncoding).name();
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
throw new UserError("Unsupported encoding " + defaultEncoding + ".", e);
}
return res;
}
public VirtualSourceRoot getVirtualSourceRoot() {
return virtualSourceRoot;
}
public ExtractorConfig withVirtualSourceRoot(VirtualSourceRoot virtualSourceRoot) {
ExtractorConfig res = new ExtractorConfig(this);
res.virtualSourceRoot = virtualSourceRoot;
return res;
}
@Override
public String toString() {
return "ExtractorConfig [ecmaVersion="
+ ecmaVersion
+ ", externs="
+ externs
+ ", platform="
+ platform
+ ", mozExtensions="
+ mozExtensions
+ ", jscript="
+ jscript
+ ", jsx="
+ jsx
+ ", esnext="
+ esnext
+ ", v8Extensions="
+ v8Extensions
+ ", e4x="
+ e4x
+ ", tolerateParseErrors="
+ tolerateParseErrors
+ ", htmlHandling="
+ htmlHandling
+ ", fileType="
+ fileType
+ ", sourceType="
+ sourceType
+ ", extractLines="
+ extractLines
+ ", typescriptMode="
+ typescriptMode
+ ", defaultEncoding="
+ defaultEncoding
+ ", virtualSourceRoot="
+ virtualSourceRoot
+ "]";
}
}
| 14,054 | 26.612967 | 99 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/StmtKinds.java | package com.semmle.js.extractor;
import com.semmle.js.ast.DefaultVisitor;
import com.semmle.js.ast.ForInStatement;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.util.exception.CatastrophicError;
import java.util.LinkedHashMap;
import java.util.Map;
/** Map from SpiderMonkey statement types to the numeric kinds used in the DB scheme. */
public class StmtKinds {
private static final Map<String, Integer> stmtKinds = new LinkedHashMap<String, Integer>();
static {
stmtKinds.put("EmptyStatement", 0);
stmtKinds.put("BlockStatement", 1);
stmtKinds.put("ExpressionStatement", 2);
stmtKinds.put("IfStatement", 3);
stmtKinds.put("LabeledStatement", 4);
stmtKinds.put("BreakStatement", 5);
stmtKinds.put("ContinueStatement", 6);
stmtKinds.put("WithStatement", 7);
stmtKinds.put("SwitchStatement", 8);
stmtKinds.put("ReturnStatement", 9);
stmtKinds.put("ThrowStatement", 10);
stmtKinds.put("TryStatement", 11);
stmtKinds.put("WhileStatement", 12);
stmtKinds.put("DoWhileStatement", 13);
stmtKinds.put("ForStatement", 14);
stmtKinds.put("ForInStatement", 15);
stmtKinds.put("DebuggerStatement", 16);
stmtKinds.put("FunctionDeclaration", 17);
stmtKinds.put("SwitchCase", 19);
stmtKinds.put("CatchClause", 20);
stmtKinds.put("ForOfStatement", 21);
stmtKinds.put("LetStatement", 24);
stmtKinds.put("ForEachStatement", 25);
stmtKinds.put("ClassDeclaration", 26);
stmtKinds.put("ImportDeclaration", 27);
stmtKinds.put("ExportAllDeclaration", 28);
stmtKinds.put("ExportDefaultDeclaration", 29);
stmtKinds.put("ExportNamedDeclaration", 30);
stmtKinds.put("NamespaceDeclaration", 31);
stmtKinds.put("ImportWholeDeclaration", 32);
stmtKinds.put("ExportWholeDeclaration", 33);
stmtKinds.put("InterfaceDeclaration", 34);
stmtKinds.put("TypeAliasDeclaration", 35);
stmtKinds.put("EnumDeclaration", 36);
stmtKinds.put("ExternalModuleDeclaration", 37);
stmtKinds.put("ExportAsNamespaceDeclaration", 38);
stmtKinds.put("GlobalAugmentationDeclaration", 39);
}
private static final Map<String, Integer> declKinds = new LinkedHashMap<String, Integer>();
static {
declKinds.put("var", 18);
declKinds.put("const", 22);
declKinds.put("let", 23);
}
public static int getStmtKind(final Statement stmt) {
Integer kind =
stmt.accept(
new DefaultVisitor<Void, Integer>() {
@Override
public Integer visit(Statement nd, Void v) {
return stmtKinds.get(nd.getType());
}
@Override
public Integer visit(VariableDeclaration nd, Void v) {
return declKinds.get(nd.getKind());
}
@Override
public Integer visit(ForInStatement nd, Void c) {
return stmtKinds.get(nd.isEach() ? "ForEachStatement" : nd.getType());
}
},
null);
if (kind == null) throw new CatastrophicError("Unsupported statement kind: " + stmt.getClass());
return kind;
}
}
| 3,160 | 35.333333 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/IExtractor.java | package com.semmle.js.extractor;
import java.io.IOException;
/** Generic extractor interface. */
public interface IExtractor {
/**
* Extract a snippet of code whose textual information is provided by the given {@link
* TextualExtractor}, and return information about the number of lines of code and the number of
* lines of comments extracted.
*/
public LoCInfo extract(TextualExtractor textualExtractor) throws IOException;
}
| 445 | 30.857143 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/FileExtractor.java | package com.semmle.js.extractor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
import com.semmle.js.extractor.ExtractionMetrics.ExtractionPhase;
import com.semmle.js.extractor.trapcache.CachingTrapWriter;
import com.semmle.js.extractor.trapcache.ITrapCache;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.files.FileUtil;
import com.semmle.util.io.WholeIO;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.TrapWriter.Label;
/**
* The file extractor extracts a single file and handles source archive population and TRAP caching;
* it delegates to the appropriate {@link IExtractor} for extracting the contents of the file.
*/
public class FileExtractor {
/**
* Pattern to use on the shebang line of a script to identify whether it is a Node.js script.
*
* <p>There are many different ways of invoking the Node.js interpreter (directly, through {@code
* env}, with or without flags, with or without modified environment, etc.), so we simply look for
* the word {@code "node"} or {@code "nodejs"}.
*/
private static final Pattern NODE_INVOCATION = Pattern.compile("\\bnode(js)?\\b");
/** A pattern that matches strings starting with `{ "...":`, suggesting JSON data. */
public static final Pattern JSON_OBJECT_START =
Pattern.compile("^(?s)\\s*\\{\\s*\"([^\"]|\\\\.)*\"\\s*:.*");
/** The charset for decoding UTF-8 strings. */
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
/** Information about supported file types. */
public static enum FileType {
HTML(".htm", ".html", ".xhtm", ".xhtml", ".vue") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new HTMLExtractor(config, state);
}
@Override
public String toString() {
return "html";
}
},
JS(".js", ".jsx", ".mjs", ".es6", ".es") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new ScriptExtractor(config);
}
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (super.contains(f, lcExt, config)) return true;
// detect Node.js scripts that are meant to be run from
// the command line and do not have a `.js` extension
if (f.isFile() && lcExt.isEmpty()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String firstLine = br.readLine();
// do a cheap check first
if (firstLine != null && firstLine.startsWith("#!")) {
// now do the slightly more expensive one
return NODE_INVOCATION.matcher(firstLine).find();
}
} catch (IOException e) {
Exceptions.ignore(e, "We simply skip this file.");
}
}
return false;
}
@Override
public String toString() {
return "javascript";
}
},
JSON(".json") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new JSONExtractor(config);
}
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (super.contains(f, lcExt, config)) return true;
// detect JSON-encoded configuration files whose name starts with `.` and ends with `rc`
// (e.g., `.eslintrc` or `.babelrc`)
if (f.isFile() && f.getName().matches("\\..*rc")) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
// check whether the first two non-empty lines look like the start of a JSON object
// (two lines because the opening brace is usually on a line by itself)
StringBuilder firstTwoLines = new StringBuilder();
for (int i = 0; i < 2; ) {
String nextLine = br.readLine();
if (nextLine == null) break;
nextLine = nextLine.trim();
if (!nextLine.isEmpty()) {
firstTwoLines.append(nextLine);
++i;
}
}
return JSON_OBJECT_START.matcher(firstTwoLines).matches();
} catch (IOException e) {
Exceptions.ignore(e, "We simply skip this file.");
}
}
return false;
}
@Override
public String toString() {
return "json";
}
},
TYPESCRIPT(".ts", ".tsx") {
@Override
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
if (config.getTypeScriptMode() == TypeScriptMode.NONE) return false;
// Read the beginning of the file to guess the file type.
if (hasBadFileHeader(f, lcExt, config)) {
return false;
}
return super.contains(f, lcExt, config);
}
/** Number of bytes to read from the beginning of a ".ts" file for sniffing its file type. */
private static final int fileHeaderSize = 128;
private boolean hasBadFileHeader(File f, String lcExt, ExtractorConfig config) {
if (!".ts".equals(lcExt)) {
return false;
}
try (FileInputStream fis = new FileInputStream(f)) {
byte[] bytes = new byte[fileHeaderSize];
int length = fis.read(bytes);
if (length == -1) return false;
// Avoid invalid or unprintable UTF-8 files.
if (config.getDefaultEncoding().equals("UTF-8") && hasUnprintableUtf8(bytes, length)) {
return true;
}
// Avoid trying to extract XML files.
if (isXml(bytes, length)) return true;
// Avoid files with an unrecognized shebang header.
if (hasUnrecognizedShebang(bytes, length)) {
return true;
}
// Avoid Touchstone files
if (isTouchstone(bytes, length)) return true;
return false;
} catch (IOException e) {
Exceptions.ignore(e, "Let extractor handle this one.");
}
return false;
}
/** Returns the index after the initial BOM, if any, otherwise 0. */
private int skipBOM(byte[] bytes, int length) {
if (length >= 2
&& (bytes[0] == (byte) 0xfe && bytes[1] == (byte) 0xff
|| bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xfe)) {
return 2;
} else {
return 0;
}
}
private boolean isXml(byte[] bytes, int length) {
int startIndex = skipBOM(bytes, length);
// Check for `<` encoded in Ascii/UTF-8 or litte-endian UTF-16.
if (startIndex < length && bytes[startIndex] == '<') {
return true;
}
// Check for `<` encoded in big-endian UTF-16
if (startIndex + 1 < length && bytes[startIndex] == 0 && bytes[startIndex + 1] == '<') {
return true;
}
return false;
}
private boolean isTouchstone(byte[] bytes, int length) {
String s = new String(bytes, 0, length, StandardCharsets.US_ASCII);
return s.startsWith("! TOUCHSTONE file ") || s.startsWith("[Version] 2.0");
}
/**
* Returns true if the byte sequence contains invalid UTF-8 or unprintable ASCII characters.
*/
private boolean hasUnprintableUtf8(byte[] bytes, int length) {
// Constants for bytes with N high-order 1-bits.
// They are typed as `int` as the subsequent byte-to-int promotion would
// otherwise fill the high-order `int` bits with 1s.
final int high1 = 0b10000000;
final int high2 = 0b11000000;
final int high3 = 0b11100000;
final int high4 = 0b11110000;
final int high5 = 0b11111000;
int startIndex = skipBOM(bytes, length);
for (int i = startIndex; i < length; ++i) {
int b = bytes[i];
if ((b & high1) == 0) { // 0xxxxxxx is an ASCII character
// ASCII values 0-31 are unprintable, except 9-13 are whitespace.
// 127 is the unprintable DEL character.
if (b <= 8 || 14 <= b && b <= 31 || b == 127) {
return true;
}
} else {
// Check for malformed UTF-8 multibyte code point
int trailingBytes = 0;
if ((b & high3) == high2) {
trailingBytes = 1; // 110xxxxx 10xxxxxx
} else if ((b & high4) == high3) {
trailingBytes = 2; // 1110xxxx 10xxxxxx 10xxxxxx
} else if ((b & high5) == high4) {
trailingBytes = 3; // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
} else {
return true; // 10xxxxxx and 11111xxx are not valid here.
}
// Trailing bytes must be of form 10xxxxxx
while (trailingBytes > 0) {
++i;
--trailingBytes;
if (i >= length) {
return false;
}
if ((bytes[i] & high2) != high1) {
return true;
}
}
}
}
return false;
}
/**
* Returns true if the byte sequence starts with a shebang line that is not recognized as a
* JavaScript interpreter.
*/
private boolean hasUnrecognizedShebang(byte[] bytes, int length) {
// Shebangs preceded by a BOM aren't recognized in UNIX, but the BOM might only
// be present in the source file, to be stripped out in the build process.
int startIndex = skipBOM(bytes, length);
if (startIndex + 2 >= length) return false;
if (bytes[startIndex] != '#' || bytes[startIndex + 1] != '!') {
return false;
}
int endOfLine = -1;
for (int i = startIndex; i < length; ++i) {
if (bytes[i] == '\r' || bytes[i] == '\n') {
endOfLine = i;
break;
}
}
if (endOfLine == -1) {
// The shebang is either very long or there are no other lines in the file.
// Treat this as unrecognized.
return true;
}
// Extract the shebang text
int startOfText = startIndex + "#!".length();
int lengthOfText = endOfLine - startOfText;
String text = new String(bytes, startOfText, lengthOfText, UTF8_CHARSET);
// Check if the shebang is a recognized JavaScript intepreter.
return !NODE_INVOCATION.matcher(text).find();
}
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new TypeScriptExtractor(config, state);
}
@Override
public String toString() {
return "typescript";
}
@Override
public boolean isTrapCachingAllowed() {
return false; // Type information cannot be cached per-file.
}
},
YAML(".raml", ".yaml", ".yml") {
@Override
public IExtractor mkExtractor(ExtractorConfig config, ExtractorState state) {
return new YAMLExtractor(config);
}
@Override
public String toString() {
return "yaml";
}
};
/** The file extensions (lower-case, including leading dot) corresponding to this file type. */
private final Set<String> extensions = new LinkedHashSet<String>();
private FileType(String... extensions) {
for (String extension : extensions) this.extensions.add(extension);
}
public Set<String> getExtensions() {
return extensions;
}
/** Construct an extractor for this file type with the appropriate configuration settings. */
public abstract IExtractor mkExtractor(ExtractorConfig config, ExtractorState state);
/** Determine the {@link FileType} for a given file. */
public static FileType forFile(File f, ExtractorConfig config) {
String lcExt = StringUtil.lc(FileUtil.extension(f));
for (FileType tp : values()) if (tp.contains(f, lcExt, config)) return tp;
return null;
}
/** Determine the {@link FileType} for a given file based on its extension only. */
public static FileType forFileExtension(File f) {
String lcExt = StringUtil.lc(FileUtil.extension(f));
for (FileType tp : values())
if (tp.getExtensions().contains(lcExt)) {
return tp;
}
return null;
}
/**
* Is the given file of this type?
*
* <p>For convenience, the lower-case file extension is also passed as an argument.
*/
protected boolean contains(File f, String lcExt, ExtractorConfig config) {
return extensions.contains(lcExt);
}
/**
* Can we cache the TRAP output of this file?
*
* <p>Caching is disabled for TypeScript files as they depend on type information from other
* files.
*/
public boolean isTrapCachingAllowed() {
return true;
}
/** The names of all defined {@linkplain FileType}s. */
public static final Set<String> allNames = new LinkedHashSet<String>();
static {
for (FileType ft : FileType.values()) allNames.add(ft.name());
}
}
private final ExtractorConfig config;
private final ExtractorOutputConfig outputConfig;
private final ITrapCache trapCache;
public FileExtractor(
ExtractorConfig config, ExtractorOutputConfig outputConfig, ITrapCache trapCache) {
this.config = config;
this.outputConfig = outputConfig;
this.trapCache = trapCache;
}
public ExtractorConfig getConfig() {
return config;
}
public boolean supports(File f) {
return config.hasFileType() || FileType.forFile(f, config) != null;
}
/** @return the number of lines of code extracted, or {@code null} if the file was cached */
public Integer extract(File f, ExtractorState state) throws IOException {
FileSnippet snippet = state.getSnippets().get(f.toPath());
if (snippet != null) {
return this.extractSnippet(f.toPath(), snippet, state);
}
// populate source archive
String source = new WholeIO(config.getDefaultEncoding()).strictread(f);
outputConfig.getSourceArchive().add(f, source);
// extract language-independent bits
TrapWriter trapwriter = outputConfig.getTrapWriterFactory().mkTrapWriter(f);
Label fileLabel = trapwriter.populateFile(f);
LocationManager locationManager = new LocationManager(f, trapwriter, fileLabel);
locationManager.emitFileLocation(fileLabel, 0, 0, 0, 0);
// now extract the contents
return extractContents(f, fileLabel, source, locationManager, state);
}
/**
* Extract the contents of a file that is a snippet from another file.
*
* <p>A trap file will be derived from the snippet file, but its file label, source locations, and
* source archive entry are based on the original file.
*/
private Integer extractSnippet(Path file, FileSnippet origin, ExtractorState state) throws IOException {
TrapWriter trapwriter = outputConfig.getTrapWriterFactory().mkTrapWriter(file.toFile());
File originalFile = origin.getOriginalFile().toFile();
Label fileLabel = trapwriter.populateFile(originalFile);
LocationManager locationManager = new LocationManager(originalFile, trapwriter, fileLabel);
locationManager.setStart(origin.getLine(), origin.getColumn());
String source = new WholeIO(config.getDefaultEncoding()).strictread(file);
return extractContents(file.toFile(), fileLabel, source, locationManager, state);
}
/**
* Extract the contents of a file, potentially making use of cached information.
*
* <p>TRAP files can be logically split into two parts: a location-dependent prelude containing
* all the `files`, `folders` and `containerparent` tuples, and a content-dependent main part
* containing all the rest, which does not depend on the source file location at all. Locations in
* the main part do, of course, refer to the source file's ID, but they do so via its symbolic
* label, which is always #10000.
*
* <p>We only cache the content-dependent part, which makes up the bulk of the TRAP file anyway.
* The location-dependent part is emitted from scratch every time by the {@link #extract(File,
* ExtractorState)} method above.
*
* <p>In order to keep labels in the main part independent of the file's location, we bump the
* TRAP label counter to a known value (currently 20000) after the location-dependent part has
* been emitted. If the counter should already be larger than that (which is theoretically
* possible with insanely deeply nested directories), we have to skip caching.
*
* <p>Also note that we support extraction with TRAP writer factories that are not file-backed;
* obviously, no caching is done in that scenario.
*/
private Integer extractContents(
File extractedFile, Label fileLabel, String source, LocationManager locationManager, ExtractorState state)
throws IOException {
ExtractionMetrics metrics = new ExtractionMetrics();
metrics.startPhase(ExtractionPhase.FileExtractor_extractContents);
metrics.setLength(source.length());
metrics.setFileLabel(fileLabel);
TrapWriter trapwriter = locationManager.getTrapWriter();
FileType fileType = getFileType(extractedFile);
File cacheFile = null, // the cache file for this extraction
resultFile = null; // the final result TRAP file for this extraction
if (bumpIdCounter(trapwriter)) {
resultFile = outputConfig.getTrapWriterFactory().getTrapFileFor(extractedFile);
}
// check whether we can perform caching
if (resultFile != null && fileType.isTrapCachingAllowed()) {
cacheFile = trapCache.lookup(source, config, fileType);
}
boolean canUseCacheFile = cacheFile != null;
boolean canReuseCacheFile = canUseCacheFile && cacheFile.exists();
metrics.setCacheFile(cacheFile);
metrics.setCanReuseCacheFile(canReuseCacheFile);
metrics.writeDataToTrap(trapwriter);
if (canUseCacheFile) {
FileUtil.close(trapwriter);
if (canReuseCacheFile) {
FileUtil.append(cacheFile, resultFile);
return null;
}
// not in the cache yet, so use a caching TRAP writer to
// put the data into the cache and append it to the result file
trapwriter = new CachingTrapWriter(cacheFile, resultFile);
bumpIdCounter(trapwriter);
// re-initialise the location manager, since it keeps a reference to the TRAP writer
locationManager = new LocationManager(extractedFile, trapwriter, locationManager.getFileLabel());
}
// now do the extraction itself
boolean successful = false;
try {
IExtractor extractor = fileType.mkExtractor(config, state);
TextualExtractor textualExtractor =
new TextualExtractor(
trapwriter, locationManager, source, config.getExtractLines(), metrics, extractedFile);
LoCInfo loc = extractor.extract(textualExtractor);
int numLines = textualExtractor.isSnippet() ? 0 : textualExtractor.getNumLines();
int linesOfCode = loc.getLinesOfCode(), linesOfComments = loc.getLinesOfComments();
trapwriter.addTuple("numlines", fileLabel, numLines, linesOfCode, linesOfComments);
trapwriter.addTuple("filetype", fileLabel, fileType.toString());
metrics.stopPhase(ExtractionPhase.FileExtractor_extractContents);
metrics.writeTimingsToTrap(trapwriter);
successful = true;
return linesOfCode;
} finally {
if (!successful && trapwriter instanceof CachingTrapWriter)
((CachingTrapWriter) trapwriter).discard();
FileUtil.close(trapwriter);
}
}
public FileType getFileType(File f) {
return config.hasFileType()
? FileType.valueOf(config.getFileType())
: FileType.forFile(f, config);
}
/**
* Bump trap ID counter to separate path-dependent and path-independent parts of the TRAP file.
*
* @return true if the counter was successfully bumped
*/
public boolean bumpIdCounter(TrapWriter trapwriter) {
return trapwriter.bumpIdCount(20000);
}
}
| 20,434 | 36.564338 | 112 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/JSXTests.java | package com.semmle.js.extractor.test;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.semmle.jcorn.SyntaxError;
import com.semmle.jcorn.jsx.JSXOptions;
import com.semmle.jcorn.jsx.JSXParser;
import com.semmle.js.ast.AST2JSON;
import com.semmle.js.ast.Program;
import com.semmle.util.files.FileUtil;
import com.semmle.util.io.WholeIO;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Tests for the JSX parser, automatically generated from the acorn-jsx test suite as described in
* <code>parser-tests/jcorn-jsx/README.md</code>.
*/
@RunWith(Parameterized.class)
public class JSXTests extends ASTMatchingTests {
private static final File BASE = new File("parser-tests/jcorn-jsx").getAbsoluteFile();
@Parameters(name = "{0}")
public static Iterable<Object[]> tests() {
List<Object[]> testData = new ArrayList<Object[]>();
// iterate over all tests
for (File test : BASE.listFiles(FileUtil.extensionFilter(true, ".js"))) {
String testName = FileUtil.basename(test);
JSXOptions options = new JSXOptions().allowNamespacedObjects(false);
File optionsFile = new File(test.getParentFile(), testName + ".options.json");
if (optionsFile.exists()) {
JsonObject optionsJson =
new JsonParser().parse(new WholeIO().strictread(optionsFile)).getAsJsonObject();
if (optionsJson.has("allowNamespacedObjects"))
options =
options.allowNamespacedObjects(
optionsJson.get("allowNamespacedObjects").getAsBoolean());
if (optionsJson.has("allowNamespaces"))
options = options.allowNamespaces(optionsJson.get("allowNamespaces").getAsBoolean());
}
JsonObject expectedAST;
File expectedASTFile = new File(test.getParentFile(), testName + ".ast");
if (expectedASTFile.exists())
expectedAST =
new JsonParser().parse(new WholeIO().strictread(expectedASTFile)).getAsJsonObject();
else expectedAST = null;
String expectedFailure;
File expectedFailureFile = new File(test.getParentFile(), testName + ".fail");
if (expectedFailureFile.exists())
expectedFailure = new WholeIO().strictread(expectedFailureFile).trim();
else expectedFailure = null;
testData.add(new Object[] {testName, options, expectedAST, expectedFailure});
}
return testData;
}
private final String testName;
private final JSXOptions options;
private final JsonObject expectedAST;
private final String expectedFailure;
public JSXTests(
String testName, JSXOptions options, JsonObject expectedAST, String expectedFailure) {
this.testName = testName;
this.options = options;
this.expectedAST = expectedAST;
this.expectedFailure = expectedFailure;
}
@Test
public void runtest() {
File inputFile = new File(BASE, testName + ".js");
String input = new WholeIO().strictread(inputFile);
try {
Program actualProgram = new JSXParser(options, input, 0).parse();
JsonElement actualAST = AST2JSON.convert(actualProgram);
assertMatch("<root>", expectedAST, actualAST);
} catch (SyntaxError e) {
Assert.assertEquals(expectedFailure, e.getMessage());
}
}
}
| 3,470 | 35.15625 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/ClassPropertiesTests.java | package com.semmle.js.extractor.test;
import org.junit.Test;
/**
* Tests for parsing class properties.
*
* <p>Most tests are automatically derived from the Babylon test suite as described in <code>
* parser-tests/babylon/README.md</code>.
*/
public class ClassPropertiesTests extends ASTMatchingTests {
@Test
public void testASIFailureComputed() {
babylonTest("experimental/class-properties/asi-failure-computed");
}
@Test
public void testASIFailureGenerator() {
babylonTest("experimental/class-properties/asi-failure-generator");
}
@Test
public void testASISuccess() {
babylonTest("experimental/class-properties/asi-success");
}
@Test
public void test43() {
babylonTest("experimental/uncategorised/43");
}
@Test
public void test44() {
babylonTest("experimental/uncategorised/44");
}
@Test
public void test45() {
babylonTest("experimental/uncategorised/45");
}
@Test
public void test46() {
babylonTest("experimental/uncategorised/46");
}
}
| 1,023 | 20.787234 | 93 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/ASTMatchingTests.java | package com.semmle.js.extractor.test;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.semmle.jcorn.ESNextParser;
import com.semmle.jcorn.Options;
import com.semmle.jcorn.SyntaxError;
import com.semmle.js.ast.AST2JSON;
import com.semmle.js.ast.Program;
import com.semmle.util.io.WholeIO;
import java.io.File;
import java.util.Iterator;
import java.util.Map.Entry;
import org.junit.Assert;
/** Base class for tests that use Acorn-like AST templates to specify expected test output. */
public abstract class ASTMatchingTests {
/**
* Assert that the given actual sub-AST matches the expected AST template, where {@code path} is
* the path from the root to the sub-AST.
*/
protected void assertMatch(String path, JsonElement expected, JsonElement actual) {
if (expected == null) Assert.assertNull(path + ": null != " + actual, actual);
if (expected instanceof JsonPrimitive || expected instanceof JsonNull)
Assert.assertEquals(path, expected.toString(), actual.toString());
if (expected instanceof JsonArray) {
Assert.assertTrue(path + ": " + expected + " != " + actual, actual instanceof JsonArray);
Iterator<JsonElement> expectedElements = ((JsonArray) expected).iterator();
Iterator<JsonElement> actualElements = ((JsonArray) actual).iterator();
int elt = 0;
while (expectedElements.hasNext()) {
String newPath = path + "[" + elt++ + "]";
Assert.assertTrue(newPath + ": missing", actualElements.hasNext());
assertMatch(newPath, expectedElements.next(), actualElements.next());
}
}
if (expected instanceof JsonObject) {
Assert.assertTrue(path + ": " + expected + " != " + actual, actual instanceof JsonObject);
JsonObject actualObject = (JsonObject) actual;
for (Entry<String, JsonElement> expectedProp : ((JsonObject) expected).entrySet()) {
String key = expectedProp.getKey();
JsonElement value = expectedProp.getValue();
String newPath = path + "." + key;
Assert.assertTrue(newPath + ": missing", actualObject.has(key));
assertMatch(newPath, value, actualObject.get(key));
}
}
}
private static final File BABYLON_BASE = new File("parser-tests/babylon").getAbsoluteFile();
protected void babylonTest(String dir) {
babylonTest(dir, new Options().esnext(true));
}
protected void babylonTest(String dir, Options options) {
File actual = new File(new File(BABYLON_BASE, dir), "actual.js");
String actualSrc = new WholeIO().strictread(actual);
JsonElement actualJSON;
try {
Program actualAST = new ESNextParser(options, actualSrc, 0).parse();
actualJSON = AST2JSON.convert(actualAST);
} catch (SyntaxError e) {
actualJSON = new JsonPrimitive(e.getMessage());
}
File expected = new File(actual.getParentFile(), "expected.ast");
JsonElement expectedJSON;
if (expected.exists()) {
String expectedSrc = new WholeIO().strictread(expected);
expectedJSON = new JsonParser().parse(expectedSrc).getAsJsonObject();
} else {
File expectedErrFile = new File(actual.getParentFile(), "expected.error");
String expectedErrMsg = new WholeIO().strictread(expectedErrFile).trim();
expectedJSON = new JsonPrimitive(expectedErrMsg);
}
assertMatch("<root>", expectedJSON, actualJSON);
}
}
| 3,525 | 39.068182 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/NumericSeparatorTests.java | package com.semmle.js.extractor.test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.semmle.jcorn.ESNextParser;
import com.semmle.jcorn.Options;
import com.semmle.jcorn.SyntaxError;
import com.semmle.js.ast.ExpressionStatement;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.Program;
import org.junit.Test;
public class NumericSeparatorTests {
private void test(String src, Integer numVal) {
try {
Program p = new ESNextParser(new Options().esnext(true), src, 0).parse();
assertNotNull(numVal);
assertEquals(1, p.getBody().size());
assertTrue(p.getBody().get(0) instanceof ExpressionStatement);
ExpressionStatement exprStmt = (ExpressionStatement) p.getBody().get(0);
assertTrue(exprStmt.getExpression() instanceof Literal);
assertEquals(numVal.longValue(), ((Literal) exprStmt.getExpression()).getValue());
} catch (SyntaxError e) {
assertNull(e.toString(), numVal);
}
}
@Test
public void test() {
test("0b_", null);
test("0b0_1", 0b01);
test("0B0_1", 0b01);
test("0b0_10", 0b010);
test("0B0_10", 0b010);
test("0b01_0", 0b010);
test("0B01_0", 0b010);
test("0b01_00", 0b0100);
test("0B01_00", 0b0100);
test("0b0__0", null);
test("0b0_", null);
}
}
| 1,362 | 29.288889 | 88 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/TrapTests.java | package com.semmle.js.extractor.test;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.semmle.js.extractor.ExtractorState;
import com.semmle.js.extractor.Main;
import com.semmle.util.data.Pair;
import com.semmle.util.data.StringUtil;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.io.WholeIO;
import com.semmle.util.srcarchive.DummySourceArchive;
import com.semmle.util.trap.ITrapWriterFactory;
import com.semmle.util.trap.TrapWriter;
import com.semmle.util.trap.pathtransformers.ProjectLayoutTransformer;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class TrapTests {
private static final File BASE = new File("tests").getAbsoluteFile();
@Parameters(name = "{0}:{1}")
public static Iterable<Object[]> tests() {
List<Object[]> testData = new ArrayList<Object[]>();
// iterate over all test groups
List<String> testGroups = Arrays.asList(BASE.list());
testGroups.sort(Comparator.naturalOrder());
for (String testgroup : testGroups) {
File root = new File(BASE, testgroup);
if (root.isDirectory()) {
// check for options.json file and process it if it exists
List<String> options = new ArrayList<String>();
File optionsFile = new File(root, "options.json");
if (optionsFile.exists()) {
JsonParser p = new JsonParser();
JsonObject jsonOpts = p.parse(new WholeIO().strictread(optionsFile)).getAsJsonObject();
for (Entry<String, JsonElement> e : jsonOpts.entrySet()) {
JsonElement v = e.getValue();
if (v instanceof JsonPrimitive) {
JsonPrimitive pv = (JsonPrimitive) v;
if (pv.isBoolean() && pv.getAsBoolean()) {
options.add("--" + e.getKey());
} else {
options.add("--" + e.getKey());
options.add(pv.getAsString());
}
} else {
Assert.assertTrue(v instanceof JsonArray);
JsonArray a = (JsonArray) v;
for (JsonElement elt : a) {
options.add("--" + e.getKey());
options.add(elt.getAsString());
}
}
}
}
File inputDir = new File(root, "input");
File jsconfigFile = new File(inputDir, "tsconfig.json");
if (jsconfigFile.exists()) {
// create a single test with all files in the group
testData.add(new Object[] {testgroup, "tsconfig", new ArrayList<String>(options)});
} else {
// create isolated tests for each input file in the group
List<String> tests = Arrays.asList(inputDir.list());
tests.sort(Comparator.naturalOrder());
for (String testfile : tests) {
testData.add(new Object[] {testgroup, testfile, new ArrayList<String>(options)});
}
}
}
}
return testData;
}
private final String testgroup, testname;
private final List<String> options;
private static String userDir;
private static ExtractorState state;
public TrapTests(String testgroup, String testname, List<String> options) {
this.testgroup = testgroup;
this.testname = testname;
this.options = options;
}
@BeforeClass
public static void saveUserDir() {
userDir = System.getProperty("user.dir");
}
@BeforeClass
public static void setupState() {
state = new ExtractorState();
}
@AfterClass
public static void restoreUserDir() {
System.setProperty("user.dir", userDir);
}
@Test
public void runtest() {
state.reset();
File testdir = new File(BASE, testgroup);
File inputDir = new File(testdir, "input");
File inputFile = new File(inputDir, testname);
final File outputDir = new File(testdir, "output/trap");
System.setProperty("user.dir", inputFile.getParent());
options.add("--extract-program-text");
options.add("--quiet");
if (new File(inputDir, "tsconfig.json").exists()) {
// Use full extractor on entire directory.
options.add("--typescript-full");
options.add(inputDir.getAbsolutePath());
} else {
// Use basic extractor on a single file.
options.add("--typescript");
options.add(inputFile.getAbsolutePath());
}
final List<Pair<String, String>> expectedVsActual = new ArrayList<Pair<String, String>>();
Main main =
new Main(
new ExtractorOutputConfig(
new ITrapWriterFactory() {
@Override
public TrapWriter mkTrapWriter(final File f) {
final StringWriter sw = new StringWriter();
ProjectLayoutTransformer transformer =
new ProjectLayoutTransformer(new File(BASE, "project-layout"));
return new TrapWriter(sw, transformer) {
@Override
public void close() {
super.close();
// convert to and from UTF-8 to mimick treatment of unencodable characters
byte[] actual_utf8_bytes = StringUtil.stringToBytes(sw.toString());
String actual = new String(actual_utf8_bytes, Charset.forName("UTF-8"));
File trap = new File(outputDir, f.getName() + ".trap");
boolean replaceExpectedOutput = false;
if (replaceExpectedOutput) {
System.out.println("Replacing expected output for " + trap);
new WholeIO().strictwrite(trap, actual);
}
String expected = new WholeIO().strictreadText(trap);
expectedVsActual.add(Pair.make(expected, actual));
}
@Override
public void addTuple(String tableName, Object... values) {
if ("extraction_data".equals(tableName)
|| "extraction_time".equals(tableName)) {
// ignore non-deterministic tables
return;
}
super.addTuple(tableName, values);
}
};
}
@Override
public File getTrapFileFor(File f) {
return null;
}
},
new DummySourceArchive()),
state);
main.run(options.toArray(new String[options.size()]));
for (Pair<String, String> p : expectedVsActual) Assert.assertEquals(p.fst(), p.snd());
}
}
| 7,236 | 36.304124 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/FunctionSentTests.java | package com.semmle.js.extractor.test;
import org.junit.Test;
/**
* Tests for parsing <code>function.sent</code>.
*
* <p>Most tests are automatically derived from the Babylon test suite as described in <code>
* parser-tests/babylon/README.md</code>.
*/
public class FunctionSentTests extends ASTMatchingTests {
@Test
public void testInsideFunction() {
babylonTest("experimental/function-sent/inside-function");
}
@Test
public void testInsideGenerator() {
babylonTest("experimental/function-sent/inside-generator");
}
@Test
public void testInvalidProperty() {
babylonTest("experimental/function-sent/invalid-property");
}
}
| 661 | 23.518519 | 93 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/ObjectRestSpreadTests.java | package com.semmle.js.extractor.test;
import com.semmle.jcorn.CustomParser;
import com.semmle.jcorn.Options;
import com.semmle.jcorn.SyntaxError;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for parsing rest/spread properties.
*
* <p>Most tests are automatically derived from the Babylon test suite as described in <code>
* parser-tests/babylon/README.md</code>.
*/
public class ObjectRestSpreadTests extends ASTMatchingTests {
private void testFail(String input, String msg) {
try {
new CustomParser(new Options().esnext(true), input, 0).parse();
Assert.fail("Expected syntax error, but parsing succeeded.");
} catch (SyntaxError e) {
Assert.assertEquals(msg, e.getMessage());
}
}
@Test
public void test9() {
babylonTest("experimental/uncategorised/9");
}
@Test
public void test10() {
babylonTest("experimental/uncategorised/10");
}
@Test
public void test11() {
babylonTest("experimental/uncategorised/11");
}
@Test
public void test12() {
babylonTest("experimental/uncategorised/12");
}
@Test
public void test13() {
babylonTest("experimental/uncategorised/13");
}
@Test
public void testObjectRestSpread() {
babylonTest("harmony/arrow-functions/object-rest-spread");
}
@Test
public void testFail() {
testFail("({...'hi'} = {})", "Assigning to rvalue (1:5)");
}
}
| 1,396 | 22.283333 | 93 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/AutoBuildTests.java | package com.semmle.js.extractor.test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributeView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import com.semmle.js.extractor.AutoBuild;
import com.semmle.js.extractor.DependencyInstallationResult;
import com.semmle.js.extractor.ExtractorState;
import com.semmle.js.extractor.FileExtractor;
import com.semmle.js.extractor.FileExtractor.FileType;
import com.semmle.js.extractor.VirtualSourceRoot;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.UserError;
import com.semmle.util.files.FileUtil;
import com.semmle.util.files.FileUtil8;
import com.semmle.util.process.Env;
public class AutoBuildTests {
private Path SEMMLE_DIST, LGTM_SRC;
private Set<String> expected;
private Map<String, String> envVars;
/**
* Set up fake distribution and source directory and environment variables pointing to them, and
* add in a few fake externs.
*/
@Before
public void setup() throws IOException {
expected = new LinkedHashSet<>();
envVars = new LinkedHashMap<>();
// set up an empty distribution directory with an empty sub-directory for externs
SEMMLE_DIST = Files.createTempDirectory("autobuild-dist").toRealPath();
Path externs =
Files.createDirectories(Paths.get(SEMMLE_DIST.toString(), "tools", "data", "externs"));
// set up environment variables (the value of TRAP_FOLDER and SOURCE_ARCHIVE doesn't
// really matter, since we won't do any actual extraction)
envVars.put(Env.Var.SEMMLE_DIST.toString(), SEMMLE_DIST.toString());
envVars.put(Env.Var.TRAP_FOLDER.toString(), SEMMLE_DIST.toString());
envVars.put(Env.Var.SOURCE_ARCHIVE.toString(), SEMMLE_DIST.toString());
// set up an empty source directory
LGTM_SRC = Files.createTempDirectory("autobuild-src").toRealPath();
envVars.put("LGTM_SRC", LGTM_SRC.toString());
// add a few fake externs
addFile(true, externs, "a.js");
addFile(false, externs, "a.html");
addFile(true, externs, "sub", "b.js");
addFile(false, externs, "sub", "b.json");
}
/** Clean up distribution and source directory, and reset environment. */
@After
public void teardown() throws IOException {
FileUtil8.recursiveDelete(SEMMLE_DIST);
FileUtil8.recursiveDelete(LGTM_SRC);
}
/**
* Add a file under {@code root} that we either do or don't expect to be extracted, depending on
* the value of {@code extracted}. If the file is expected to be extracted, its path is added to
* {@link #expected}. If non-null, parameter {@code fileType} indicates the file type with which
* we expect the file to be extracted.
*/
private Path addFile(boolean extracted, FileType fileType, Path root, String... components)
throws IOException {
Path f = addFile(root, components);
if (extracted) {
expected.add(f + (fileType == null ? "" : ":" + fileType.toString()));
}
return f;
}
/** Add a file with default file type. */
private Path addFile(boolean extracted, Path root, String... components) throws IOException {
return addFile(extracted, null, root, components);
}
/** Create a file at the specified path under {@code root} and return it. */
private Path addFile(Path root, String... components) throws IOException {
Path p = Paths.get(root.toString(), components);
Files.createDirectories(p.getParent());
return Files.createFile(p);
}
/** Run autobuild and compare the set of actually extracted files against {@link #expected}. */
private void runTest() throws IOException {
Env.systemEnv().pushEnvironmentContext(envVars);
try {
Set<String> actual = new LinkedHashSet<>();
new AutoBuild() {
@Override
protected CompletableFuture<?> extract(FileExtractor extractor, Path file, boolean concurrent) {
String extracted = file.toString();
if (extractor.getConfig().hasFileType())
extracted += ":" + extractor.getFileType(file.toFile());
actual.add(extracted);
return CompletableFuture.completedFuture(null);
}
@Override
public void verifyTypeScriptInstallation(ExtractorState state) {}
@Override
public void extractTypeScriptFiles(
java.util.List<Path> files,
java.util.Set<Path> extractedFiles,
FileExtractors extractors) {
for (Path f : files) {
actual.add(f.toString());
}
}
@Override
protected DependencyInstallationResult preparePackagesAndDependencies(Set<Path> filesToExtract) {
// currently disabled in tests
return DependencyInstallationResult.empty;
}
@Override
protected VirtualSourceRoot makeVirtualSourceRoot() {
return VirtualSourceRoot.none; // not used in these tests
}
@Override
protected void extractXml() throws IOException {
Files.walkFileTree(
LGTM_SRC,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String ext = FileUtil.extension(file);
if (!ext.isEmpty() && getXmlExtensions().contains(ext.substring(1)))
actual.add(file.toString());
return FileVisitResult.CONTINUE;
}
});
}
}.run();
String expectedString = StringUtil.glue("\n", expected.stream().sorted().toArray());
String actualString = StringUtil.glue("\n", actual.stream().sorted().toArray());
Assert.assertEquals(expectedString, actualString);
} finally {
Env.systemEnv().popEnvironmentContext();
}
}
@Test
public void basicTest() throws IOException {
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "tst.ts");
addFile(true, LGTM_SRC, "tst.html");
addFile(false, LGTM_SRC, "tst.json");
addFile(true, LGTM_SRC, "package.json");
addFile(true, LGTM_SRC, ".eslintrc.yml");
addFile(true, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void typescript() throws IOException {
envVars.put("LGTM_INDEX_TYPESCRIPT", "basic");
addFile(true, LGTM_SRC, "tst.ts");
addFile(true, LGTM_SRC, "tst.tsx");
runTest();
}
@Test(expected = UserError.class)
public void typescriptWrongConfig() throws IOException {
envVars.put("LGTM_INDEX_TYPESCRIPT", "true");
addFile(true, LGTM_SRC, "tst.ts");
addFile(true, LGTM_SRC, "tst.tsx");
runTest();
}
@Test
public void includeFile() throws IOException {
envVars.put("LGTM_INDEX_INCLUDE", "tst.js");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFile() throws IOException {
envVars.put("LGTM_INDEX_EXCLUDE", "vendor/leftpad/index.js");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByPattern() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "exclude:**/vendor");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByPattern2() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "exclude:*/**/vendor");
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "vendor", "dep", "index.js");
addFile(false, LGTM_SRC, "vendor", "dep", "vendor", "depdep", "index.js");
runTest();
}
@Test
public void excludeFolderByPattern3() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "exclude:**/vendor\n");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByPatterns() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "exclude:foo\nexclude:**/vendor");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByName() throws IOException {
envVars.put("LGTM_INDEX_EXCLUDE", "vendor");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByName2() throws IOException {
envVars.put("LGTM_INDEX_EXCLUDE", "vendor\n");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeFolderByName3() throws IOException {
envVars.put("LGTM_INDEX_EXCLUDE", "./vendor\n");
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeByExtension() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "exclude:**/*.js");
addFile(false, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "tst.html");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
addFile(true, LGTM_SRC, "vendor", "leftpad", "index.html");
runTest();
}
@Test
public void includeByExtension() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:**/*.json");
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "tst.json");
addFile(true, LGTM_SRC, "vendor", "leftpad", "tst.json");
runTest();
}
@Test
public void includeByExtensionInRootOnly() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:*.json");
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "tst.json");
addFile(false, LGTM_SRC, "vendor", "leftpad", "tst.json");
runTest();
}
@Test
public void includeAndExclude() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:**/*.json\n" + "exclude:**/vendor");
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "tst.json");
addFile(false, LGTM_SRC, "vendor", "leftpad", "tst.json");
runTest();
}
@Test
public void excludeByClassification() throws IOException {
Path repositoryFolders = Files.createFile(SEMMLE_DIST.resolve("repositoryFolders.csv"));
List<String> csvLines = new ArrayList<>();
csvLines.add("classification,path");
csvLines.add("thirdparty," + LGTM_SRC.resolve("vendor"));
csvLines.add("external," + LGTM_SRC.resolve("foo").resolve("bar").toUri());
csvLines.add("metadata," + LGTM_SRC.resolve(".git"));
Files.write(repositoryFolders, csvLines, StandardCharsets.UTF_8);
envVars.put("LGTM_REPOSITORY_FOLDERS_CSV", repositoryFolders.toString());
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "foo", "bar", "tst.js");
addFile(false, LGTM_SRC, ".git", "tst.js");
addFile(true, LGTM_SRC, "vendor", "leftpad", "tst.js");
runTest();
}
@Test
public void excludeIncludeNested() throws IOException {
envVars.put("LGTM_INDEX_INCLUDE", ".\ntest/util");
envVars.put("LGTM_INDEX_EXCLUDE", "test\ntest/util/test");
addFile(true, LGTM_SRC, "index.js");
addFile(false, LGTM_SRC, "test", "tst.js");
addFile(false, LGTM_SRC, "test", "subtest", "tst.js");
addFile(true, LGTM_SRC, "test", "util", "util.js");
addFile(false, LGTM_SRC, "test", "util", "test", "utiltst.js");
runTest();
}
@Test
public void includeImplicitlyExcluded() throws IOException {
Path repositoryFolders = Files.createFile(SEMMLE_DIST.resolve("repositoryFolders.csv"));
List<String> csvLines = new ArrayList<>();
csvLines.add("classification,path");
csvLines.add("thirdparty," + LGTM_SRC.resolve("vendor"));
csvLines.add("external," + LGTM_SRC.resolve("foo").resolve("bar"));
csvLines.add("metadata," + LGTM_SRC.resolve(".git"));
Files.write(repositoryFolders, csvLines, StandardCharsets.UTF_8);
envVars.put("LGTM_REPOSITORY_FOLDERS_CSV", repositoryFolders.toString());
envVars.put("LGTM_INDEX_INCLUDE", ".\nfoo/bar");
addFile(true, LGTM_SRC, "tst.js");
addFile(true, LGTM_SRC, "foo", "bar", "tst.js");
addFile(false, LGTM_SRC, ".git", "tst.js");
addFile(true, LGTM_SRC, "vendor", "leftpad", "tst.js");
runTest();
}
/**
* Create a symbolic link from {@code $LGTM_SRC/link} to {@code target} and invoke {@code
* runTest}. Skip running the test if the symbolic link cannot be created.
*/
private void createSymlinkAndRunTest(String link, Path target) throws IOException {
createSymlinkAndRunTest(Paths.get(LGTM_SRC.toString(), link), target);
}
/**
* Create a symbolic link from {@code link} to {@code target} and invoke {@code runTest}. Skip
* running the test if the symbolic link cannot be created.
*/
private void createSymlinkAndRunTest(Path linkPath, Path target) throws IOException {
try {
Files.createSymbolicLink(linkPath, target);
} catch (UnsupportedOperationException | SecurityException | IOException e) {
Assume.assumeNoException("Cannot create symlinks.", e);
}
runTest();
}
@Test
public void symlinkFile() throws IOException {
Path tst_js = addFile(true, LGTM_SRC, "tst.js");
createSymlinkAndRunTest("tst_link.js", tst_js);
}
@Test
public void symlinkDir() throws IOException {
Path testFolder = Files.createTempDirectory("autobuild-test").toAbsolutePath();
try {
addFile(false, testFolder, "tst.js");
createSymlinkAndRunTest("test", testFolder);
} finally {
FileUtil8.recursiveDelete(testFolder);
}
}
@Test
public void deadSymlinkFile() throws IOException {
Path dead = Paths.get("i", "do", "not", "exist", "tst.js");
Assert.assertFalse(Files.exists(dead));
createSymlinkAndRunTest("tst_link.js", dead);
}
@Test
public void deadSymlinkDir() throws IOException {
Path dead = Paths.get("i", "do", "not", "exist");
Assert.assertFalse(Files.exists(dead));
createSymlinkAndRunTest("test", dead);
}
@Test
public void excludeByClassificationSymlink() throws IOException {
// check for robustness in case LGTM_SRC is canonicalised but repositoryFolders.csv is not
Path testFolder = Files.createTempDirectory("autobuild-test").toAbsolutePath();
Files.createDirectories(testFolder);
Path repositoryFolders = Files.createFile(SEMMLE_DIST.resolve("repositoryFolders.csv"));
List<String> csvLines = new ArrayList<>();
csvLines.add("classification,path");
csvLines.add("external," + testFolder.resolve("src").resolve("foo"));
Files.write(repositoryFolders, csvLines, StandardCharsets.UTF_8);
envVars.put("LGTM_REPOSITORY_FOLDERS_CSV", repositoryFolders.toString());
addFile(false, LGTM_SRC, "foo", "tst.js");
createSymlinkAndRunTest(testFolder.resolve("src"), LGTM_SRC);
FileUtil8.recursiveDelete(testFolder);
}
@Test
public void excludeByClassificationBadPath() throws IOException {
// check for robustness in case there are unresolvable paths in repositoryFolders.csv
Path testFolder = Files.createTempDirectory("autobuild-test").toAbsolutePath();
Files.createDirectories(testFolder);
Path repositoryFolders = Files.createFile(SEMMLE_DIST.resolve("repositoryFolders.csv"));
List<String> csvLines = new ArrayList<>();
csvLines.add("classification,path");
csvLines.add("external,no-such-path");
Files.write(repositoryFolders, csvLines, StandardCharsets.UTF_8);
envVars.put("LGTM_REPOSITORY_FOLDERS_CSV", repositoryFolders.toString());
addFile(true, LGTM_SRC, "tst.js");
runTest();
FileUtil8.recursiveDelete(testFolder);
}
/** Hide {@code p} on using {@link DosFileAttributeView} if available; otherwise do nothing. */
private void hide(Path p) throws IOException {
DosFileAttributeView attrs = Files.getFileAttributeView(p, DosFileAttributeView.class);
if (attrs != null) attrs.setHidden(true);
}
@Test
public void hiddenFolders() throws IOException {
Path tst_js = addFile(false, LGTM_SRC, ".DS_Store", "tst.js");
hide(tst_js.getParent());
runTest();
}
@Test
public void hiddenFiles() throws IOException {
Path eslintrc = addFile(true, LGTM_SRC, ".eslintrc.json");
hide(eslintrc);
runTest();
}
@Test
public void noTypescriptExtraction() throws IOException {
envVars.put("LGTM_INDEX_TYPESCRIPT", "none");
addFile(false, LGTM_SRC, "tst.ts");
addFile(false, LGTM_SRC, "sub.js", "tst.ts");
addFile(false, LGTM_SRC, "tst.js.ts");
runTest();
}
@Test
public void includeNonExistentFile() throws IOException {
envVars.put("LGTM_INDEX_INCLUDE", "tst.js");
addFile(false, LGTM_SRC, "vendor", "leftpad", "index.js");
runTest();
}
@Test
public void excludeNonExistentFile() throws IOException {
envVars.put("LGTM_INDEX_EXCLUDE", "vendor/leftpad/index.js");
addFile(true, LGTM_SRC, "tst.js");
runTest();
}
@Test
public void minifiedFilesAreExcluded() throws IOException {
addFile(true, LGTM_SRC, "admin.js");
addFile(false, LGTM_SRC, "jquery.min.js");
addFile(false, LGTM_SRC, "lib", "lodash-min.js");
addFile(true, LGTM_SRC, "compute_min.js");
runTest();
}
@Test
public void minifiedFilesCanBeReIncluded() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:**/*.min.js\ninclude:**/*-min.js");
addFile(true, LGTM_SRC, "admin.js");
addFile(true, LGTM_SRC, "jquery.min.js");
addFile(true, LGTM_SRC, "lib", "lodash-min.js");
addFile(true, LGTM_SRC, "compute_min.js");
runTest();
}
@Test
public void nodeModulesAreExcluded() throws IOException {
addFile(true, LGTM_SRC, "index.js");
addFile(false, LGTM_SRC, "node_modules", "dep", "main.js");
addFile(false, LGTM_SRC, "node_modules", "dep", "node_modules", "leftpad", "index.js");
runTest();
}
@Test
public void nodeModulesCanBeReincluded() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:**/node_modules");
addFile(true, LGTM_SRC, "index.js");
addFile(true, LGTM_SRC, "node_modules", "dep", "main.js");
addFile(true, LGTM_SRC, "node_modules", "dep", "node_modules", "leftpad", "index.js");
runTest();
}
@Test
public void bowerComponentsAreExcluded() throws IOException {
addFile(true, LGTM_SRC, "index.js");
addFile(false, LGTM_SRC, "bower_components", "dep", "main.js");
addFile(false, LGTM_SRC, "bower_components", "dep", "bower_components", "leftpad", "index.js");
runTest();
}
@Test
public void bowerComponentsCanBeReincluded() throws IOException {
envVars.put("LGTM_INDEX_FILTERS", "include:**/bower_components");
addFile(true, LGTM_SRC, "index.js");
addFile(true, LGTM_SRC, "bower_components", "dep", "main.js");
addFile(true, LGTM_SRC, "bower_components", "dep", "bower_components", "leftpad", "index.js");
runTest();
}
@Test
public void customExtensions() throws IOException {
envVars.put("LGTM_INDEX_FILETYPES", ".jsm:js\n.soy:html");
addFile(true, FileType.JS, LGTM_SRC, "tst.jsm");
addFile(false, LGTM_SRC, "tstjsm");
addFile(true, FileType.HTML, LGTM_SRC, "tst.soy");
addFile(true, LGTM_SRC, "tst.html");
addFile(true, LGTM_SRC, "tst.js");
runTest();
}
@Test
public void overrideExtension() throws IOException {
envVars.put("LGTM_INDEX_FILETYPES", ".js:typescript");
addFile(true, FileType.TYPESCRIPT, LGTM_SRC, "tst.js");
runTest();
}
@Test
public void invalidFileType() throws IOException {
envVars.put("LGTM_INDEX_FILETYPES", ".jsm:javascript");
try {
runTest();
Assert.fail("expected UserError");
} catch (UserError ue) {
Assert.assertEquals("Invalid file type 'JAVASCRIPT'.", ue.getMessage());
}
}
@Test
public void includeYaml() throws IOException {
addFile(true, LGTM_SRC, "tst.yaml");
addFile(true, LGTM_SRC, "tst.yml");
addFile(true, LGTM_SRC, "tst.raml");
runTest();
}
@Test
public void dontIncludeXmlByDefault() throws IOException {
addFile(false, LGTM_SRC, "tst.xml");
addFile(false, LGTM_SRC, "tst.qhelp");
runTest();
}
@Test
public void includeXml() throws IOException {
envVars.put("LGTM_INDEX_XML_MODE", "all");
addFile(true, LGTM_SRC, "tst.xml");
addFile(false, LGTM_SRC, "tst.qhelp");
runTest();
}
@Test
public void qhelpAsXml() throws IOException {
envVars.put("LGTM_INDEX_FILETYPES", ".qhelp:xml");
addFile(false, LGTM_SRC, "tst.xml");
addFile(true, LGTM_SRC, "tst.qhelp");
runTest();
}
@Test
public void qhelpAsXmlAndAllXml() throws IOException {
envVars.put("LGTM_INDEX_XML_MODE", "all");
envVars.put("LGTM_INDEX_FILETYPES", ".qhelp:xml");
addFile(true, LGTM_SRC, "tst.xml");
addFile(true, LGTM_SRC, "tst.qhelp");
runTest();
}
@Test
public void skipCodeQLDatabases() throws IOException {
addFile(true, LGTM_SRC, "tst.js");
addFile(false, LGTM_SRC, "db/codeql-database.yml");
addFile(false, LGTM_SRC, "db/foo.js");
runTest();
}
}
| 21,668 | 34.406863 | 105 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/ExportExtensionsTests.java | package com.semmle.js.extractor.test;
import com.semmle.jcorn.Options;
import org.junit.Test;
/**
* Tests for parsing export extensions.
*
* <p>Most tests are automatically derived from the Babylon test suite as described in <code>
* parser-tests/babylon/README.md</code>.
*/
public class ExportExtensionsTests extends ASTMatchingTests {
@Override
protected void babylonTest(String dir) {
babylonTest(dir, new Options().esnext(true).sourceType("module"));
}
@Test
public void test50() {
babylonTest("experimental/uncategorised/50");
}
@Test
public void test51() {
babylonTest("experimental/uncategorised/51");
}
@Test
public void test52() {
babylonTest("experimental/uncategorised/52");
}
@Test
public void test53() {
babylonTest("experimental/uncategorised/53");
}
@Test
public void test54() {
babylonTest("experimental/uncategorised/54");
}
}
| 917 | 20.348837 | 93 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/DecoratorTests.java | package com.semmle.js.extractor.test;
import org.junit.Test;
/**
* Tests for parsing decorators.
*
* <p>Most tests are automatically derived from the Babylon test suite as described in <code>
* parser-tests/babylon/README.md</code>.
*/
public class DecoratorTests extends ASTMatchingTests {
@Test
public void test33() {
babylonTest("experimental/uncategorised/33");
}
@Test
public void test34() {
babylonTest("experimental/uncategorised/34");
}
@Test
public void test35() {
babylonTest("experimental/uncategorised/35");
}
@Test
public void test36() {
babylonTest("experimental/uncategorised/36");
}
@Test
public void test37() {
babylonTest("experimental/uncategorised/37");
}
@Test
public void test38() {
babylonTest("experimental/uncategorised/38");
}
@Test
public void test39() {
babylonTest("experimental/uncategorised/39");
}
@Test
public void test40() {
babylonTest("experimental/uncategorised/40");
}
@Test
public void test41() {
babylonTest("experimental/uncategorised/41");
}
@Test
public void test42() {
babylonTest("experimental/uncategorised/42");
}
@Test
public void test49() {
babylonTest("experimental/uncategorised/49");
}
@Test
public void test62() {
babylonTest("experimental/uncategorised/62");
}
}
| 1,355 | 17.833333 | 93 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/RobustnessTests.java | package com.semmle.js.extractor.test;
import com.semmle.jcorn.Options;
import com.semmle.jcorn.Parser;
import com.semmle.util.io.WholeIO;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
public class RobustnessTests {
@Test
public void letLookheadTest() {
File test = new File("parser-tests/robustness/letLookahead.js");
String src = new WholeIO(StandardCharsets.UTF_8.name()).strictread(test);
new Parser(new Options(), src, 0).parse();
}
}
| 500 | 25.368421 | 77 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/OffsetTranslationTest.java | package com.semmle.js.extractor.test;
import com.semmle.js.extractor.OffsetTranslation;
import org.junit.Assert;
import org.junit.Test;
public class OffsetTranslationTest {
@Test
public void testBasic() {
OffsetTranslation table = new OffsetTranslation();
table.set(0, 10);
table.set(100, 250);
Assert.assertEquals(10, table.get(0));
Assert.assertEquals(15, table.get(5));
Assert.assertEquals(85, table.get(75));
Assert.assertEquals(109, table.get(99));
Assert.assertEquals(250, table.get(100));
Assert.assertEquals(251, table.get(101));
}
@Test
public void testLookupBefore() {
OffsetTranslation table = new OffsetTranslation();
table.set(0, 10);
table.set(100, 250);
Assert.assertEquals(9, table.get(-1));
}
@Test
public void testIdentity() {
OffsetTranslation table = new OffsetTranslation();
table.set(0, 0);
Assert.assertEquals(0, table.get(0));
Assert.assertEquals(75, table.get(75));
}
@Test
public void testDuplicateAnchor() {
OffsetTranslation table = new OffsetTranslation();
table.set(0, 0);
table.set(10, 100);
table.set(10, 100);
table.set(20, 150);
Assert.assertEquals(1, table.get(1));
Assert.assertEquals(100, table.get(10));
Assert.assertEquals(101, table.get(11));
Assert.assertEquals(150, table.get(20));
Assert.assertEquals(151, table.get(21));
}
}
| 1,406 | 26.588235 | 54 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/AllTests.java | package com.semmle.js.extractor.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
JSXTests.class,
NodeJSDetectorTests.class,
TrapTests.class,
ObjectRestSpreadTests.class,
ClassPropertiesTests.class,
FunctionSentTests.class,
DecoratorTests.class,
ExportExtensionsTests.class,
AutoBuildTests.class,
RobustnessTests.class,
NumericSeparatorTests.class
})
public class AllTests {}
| 504 | 21.954545 | 44 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/test/NodeJSDetectorTests.java | package com.semmle.js.extractor.test;
import com.semmle.js.ast.Node;
import com.semmle.js.extractor.ExtractionMetrics;
import com.semmle.js.extractor.ExtractorConfig;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.extractor.NodeJSDetector;
import com.semmle.js.parser.JSParser;
import com.semmle.js.parser.JSParser.Result;
import org.junit.Assert;
import org.junit.Test;
public class NodeJSDetectorTests {
private static final ExtractorConfig CONFIG = new ExtractorConfig(false);
private void isNodeJS(String src, boolean expected) {
Result res = JSParser.parse(CONFIG, SourceType.SCRIPT, src, new ExtractionMetrics());
Node ast = res.getAST();
Assert.assertNotNull(ast);
Assert.assertTrue(NodeJSDetector.looksLikeNodeJS(ast) == expected);
}
@Test
public void testBareRequire() {
isNodeJS("require('fs');", true);
}
@Test
public void testRequireInit() {
isNodeJS("var fs = require('fs');", true);
}
@Test
public void testRequireInit2() {
isNodeJS("var foo, fs = require('fs');", true);
}
@Test
public void testDirective() {
isNodeJS("\"use strict\"; require('fs');", true);
}
@Test
public void testComment() {
isNodeJS(
"/** My awesome package.\n"
+ "* (C) me.\n"
+ "*/\n"
+ "\n"
+ "var isArray = require(\"isArray\");",
true);
}
@Test
public void testInitialExport() {
isNodeJS("exports.foo = 0; console.log('Hello, world!');", true);
}
@Test
public void testInitialModuleExport() {
isNodeJS("module.exports.foo = 0; console.log('Hello, world!');", true);
}
@Test
public void testInitialBulkExport() {
isNodeJS("module.exports = {}; console.log('Hello, world!');", true);
}
@Test
public void testTrailingExport() {
isNodeJS("console.log('Hello, world!'); exports.foo = 0;", true);
}
@Test
public void testTrailingModuleExport() {
isNodeJS("console.log('Hello, world!'); module.exports.foo = 0;", true);
}
@Test
public void testTrailingBulkExport() {
isNodeJS("console.log('Hello, world!'); module.exports = {};", true);
}
@Test
public void testInitialNestedExport() {
isNodeJS("mystuff = module.exports = {}; mystuff.foo = 0;", true);
}
@Test
public void testInitialNestedExportInit() {
isNodeJS("var mystuff = module.exports = exports = {}; mystuff.foo = 0;", true);
}
@Test
public void testTrailingRequire() {
isNodeJS("console.log('Hello, world!'); var fs = require('fs');", true);
}
@Test
public void testSandwichedExport() {
isNodeJS("console.log('Hello'); exports.foo = 0; console.log('world!');", true);
}
@Test
public void umd() {
isNodeJS(
"(function(define) {\n"
+ " define(function (require, exports, module) {\n"
+ " var b = require('b');\n"
+ " return function () {};\n"
+ " });\n"
+ "}(\n"
+ " typeof module === 'object' && module.exports && typeof define !== 'function' ?\n"
+ " function (factory) { module.exports = factory(require, exports, module); } :\n"
+ " define\n"
+ "));",
false);
}
@Test
public void testRequirePropAccess() {
isNodeJS("var foo = require('./b').foo;", true);
}
@Test
public void testReExport() {
isNodeJS("module.exports = require('./e');", true);
}
@Test
public void testSeparateVar() {
isNodeJS("var fs; fs = require('fs');", true);
}
@Test
public void testLet() {
isNodeJS("let fs = require('fs');", true);
}
@Test
public void testSeparateLet() {
isNodeJS("let fs; fs = require('fs');", true);
}
@Test
public void testConst() {
isNodeJS("const fs = require('fs');", true);
}
@Test
public void testIife() {
isNodeJS(";(function() { require('fs'); })()", true);
}
@Test
public void testIife2() {
isNodeJS("!function() { require('fs'); }()", true);
}
@Test
public void testUMD() {
isNodeJS("(function(require) { require('fs'); })(myRequire);", false);
}
@Test
public void amdefine() {
isNodeJS(
"if (typeof define !== 'function') define = require('amdefine')(module, require);", true);
}
@Test
public void requireAndReadProp() {
isNodeJS("var readFileSync = require('fs').readFileSync;", true);
}
@Test
public void toplevelAMDRequire() {
isNodeJS("require(['foo'], function(foo) { });", false);
}
@Test
public void requireInTry() {
isNodeJS(
"var fs;"
+ "try {"
+ " fs = require('graceful-fs');"
+ "} catch(e) {"
+ " fs = require('fs');"
+ "}",
true);
}
@Test
public void requireInIf() {
isNodeJS(
"var fs;"
+ "if (useGracefulFs) {"
+ " fs = require('graceful-fs');"
+ "} else {"
+ " fs = require('fs');"
+ "}",
true);
}
@Test
public void requireAndCall() {
isNodeJS("var foo = require('foo')();", true);
}
@Test
public void requireAndCallMethod() {
isNodeJS("var foo = require('foo').bar();", true);
}
}
| 5,220 | 23.283721 | 98 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/trapcache/ITrapCache.java | package com.semmle.js.extractor.trapcache;
import com.semmle.js.extractor.ExtractorConfig;
import com.semmle.js.extractor.FileExtractor;
import java.io.File;
/** Generic TRAP cache interface. */
public interface ITrapCache {
/**
* Look up a file in the TRAP cache.
*
* @param source the content of the file
* @param config the configuration options this file will be extracted with if it is not found in
* the cache
* @param type the type of the file
* @return {@literal null} if this TRAP cache does not support caching the given file; otherwise,
* a file in the TRAP cache which may either already exist (and then is guaranteed to hold
* cached information), or does not yet exist (and should be populated by the extractor)
*/
public File lookup(String source, ExtractorConfig config, FileExtractor.FileType type);
}
| 867 | 38.454545 | 99 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/trapcache/DummyTrapCache.java | package com.semmle.js.extractor.trapcache;
import com.semmle.js.extractor.ExtractorConfig;
import com.semmle.js.extractor.FileExtractor.FileType;
import java.io.File;
/** A dummy TRAP cache that does not cache anything. */
public class DummyTrapCache implements ITrapCache {
@Override
public File lookup(String source, ExtractorConfig config, FileType type) {
return null;
}
}
| 389 | 26.857143 | 76 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/trapcache/DefaultTrapCache.java | package com.semmle.js.extractor.trapcache;
import com.semmle.js.extractor.ExtractorConfig;
import com.semmle.js.extractor.FileExtractor.FileType;
import com.semmle.util.data.Pair;
import com.semmle.util.data.StringDigestor;
import com.semmle.util.data.UnitParser;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.exception.ResourceError;
import com.semmle.util.files.FileUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/** The default TRAP cache implementation. */
public class DefaultTrapCache implements ITrapCache {
private final File trapCache;
/**
* A version identifier for the extractor whose TRAP files we are caching.
*
* <p>The same source code of the same {@link FileType} extracted twice with the same extractor
* version and under the same {@link ExtractorConfig} should yield semantically equivalent sets of
* tuples.
*/
private final String extractorVersion;
public DefaultTrapCache(String trapCache, Long sizeBound, String extractorVersion) {
this.trapCache = new File(trapCache);
this.extractorVersion = extractorVersion;
try {
initCache(sizeBound);
} catch (ResourceError | SecurityException e) {
throw new ResourceError("Could not initialize trap cache at " + trapCache, e);
}
}
/**
* Initialise the TRAP cache.
*
* <p>This creates the cache directory (if it does not exist yet), and trims the cache to fit
* within the size bounds specified in its <code>size.bounds</code> file (if specified).
*
* <p>To trim the cache size, the files in the cache are traversed in some unspecified order, and
* their sizes are summed up; if their total size exceeds the high water mark specified in <code>
* size.bounds</code>, files are deleted to reduce the cache size to less than the low water mark.
*
* <p>If any of these steps fail, we silently give up. Hence there is no guarantee that the cache
* will actually be smaller than the low water mark after initialisation.
*/
private void initCache(Long sizeBound) {
FileUtil.mkdirs(this.trapCache);
try {
Long lowWaterMark, highWaterMark;
if (sizeBound != null) {
highWaterMark = sizeBound;
lowWaterMark = (long) (0.4 * highWaterMark);
} else {
Pair<Long, Long> watermarks = readCacheSizeBounds();
if (watermarks == null) return;
lowWaterMark = watermarks.fst();
highWaterMark = watermarks.snd();
}
trimCacheToSize(lowWaterMark, highWaterMark);
} catch (IOException | SecurityException e) {
Exceptions.ignore(e, "Cache size management is optional.");
}
}
private void trimCacheToSize(long lo, long hi) {
// all `.trap.gz` files in the cache, in some unspecified order
File[] files = this.trapCache.listFiles(FileUtil.extensionFilter(true, ".trap.gz"));
// cumulative size of all files we have seen so far
long cur = 0;
// index of first file where cumulative size exceeds low water mark;
// set to files.length to indicate that the low water mark was not exceeded
int firstPastLo = files.length;
for (int i = 0; i < files.length; ++i) {
File f = files[i];
cur += f.length();
if (firstPastLo == files.length && cur > lo) firstPastLo = i;
if (cur > hi) break;
}
// if the high water mark was exceeded, delete files starting at `firstPastLo`
if (cur > hi) while (firstPastLo < files.length) files[firstPastLo++].delete();
}
/**
* Read the cache size bounds for this TRAP cache.
*
* <p>Cache size bounds are specified on the first line of a file called <code>size.bounds</code>
* in the cache directory (any subsequent lines are ignored).
*
* <p>Two bounds are specified, separated by a colon: the first is a low water mark, the second a
* high water mark. The high water mark may be omitted, in which case it defaults to the low water
* mark. Both bounds should be specified as using file size units, cf. {@link
* UnitParser#MEGABYTES}.
*
* @return a pair of file sizes in bytes, or {@code null} if the sizes could not be determined for
* whatever reason
*/
private Pair<Long, Long> readCacheSizeBounds() throws IOException {
File cacheSizeFile = new File(this.trapCache, "size.bounds");
if (!cacheSizeFile.canRead()) return null;
try (BufferedReader br = new BufferedReader(new FileReader(cacheSizeFile))) {
String firstLine = br.readLine();
if (firstLine == null) return null;
String[] sizes = firstLine.split(":");
Long lo = sizes.length < 1 ? null : asFileSize(sizes[0]);
Long hi = sizes.length < 2 ? lo : asFileSize(sizes[1]);
if (lo == null || hi == null || hi < lo) return null;
return Pair.make(lo, hi);
}
}
public static Long asFileSize(String s) {
Integer tmp = UnitParser.parseOpt(s, UnitParser.MEGABYTES);
if (tmp == null) return null;
return tmp.longValue() * 1024 * 1024;
}
@Override
public File lookup(String source, ExtractorConfig config, FileType type) {
// compute a hash for this file based on its contents and the configuration options
StringDigestor digestor = new StringDigestor();
digestor.write(extractorVersion);
digestor.write(type.toString());
digestor.write(config);
digestor.write(source);
return new File(trapCache, digestor.getDigest() + ".trap.gz");
}
}
| 5,473 | 37.822695 | 100 | java |
codeql | codeql-master/javascript/extractor/src/com/semmle/js/extractor/trapcache/CachingTrapWriter.java | package com.semmle.js.extractor.trapcache;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.files.FileUtil;
import com.semmle.util.trap.TrapWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
/**
* A trap writer for use with a trap cache.
*
* <p>A caching trap writer mainly works with two files: a result file to which tuples should be
* appended, and a cache file that should be atomically overwritten with the complete list of tuples
* produced by this writer once it is closed.
*
* <p>To achieve the latter, the trap writer writes all tuples to a temporary file first. When the
* writer is closed (and extraction has succeeded), it atomically moves the temporary file over the
* cache file.
*
* <p>This is similar to a concurrent trap writer, but a caching trap writer ensures that the trap
* file is overwritten atomically. If this is impossible, the cached file will not be updated at
* all.
*
* <p>In summary, a {@code CachingTrapWriter} keeps track of three files:
*
* <ul>
* <li>a temporary file to which tuples produced by this writer are written, referenced by field
* {@code tmpFile};
* <li>a cache file that is atomically overwritten with the contents of the temporary file when
* this writer is closed, referenced by field {@code trapFile};
* <li>a result file to which the contents of the temporary file are appended when this writer is
* closed, referenced by field {@code resultFile}.
* </ul>
*/
public class CachingTrapWriter extends TrapWriter {
private final File resultFile;
// whether extraction was successful
private boolean successful = true;
public CachingTrapWriter(File cacheFile, File resultFile) {
super(cacheFile, true);
this.resultFile = resultFile;
}
/**
* Tell the writer that extraction was not successful; the cache file and the result file will not
* be updated.
*/
public void discard() {
successful = false;
}
@Override
public void close() {
FileUtil.close(out);
try {
if (successful) {
// first append tuples from temporary file to result file (in case the move fails)
FileUtil.append(tmpFile, resultFile);
// then try to atomically move temporary file over cache file
Files.move(tmpFile.toPath(), trapFile.toPath(), StandardCopyOption.ATOMIC_MOVE);
}
} catch (IOException e) {
Exceptions.ignore(e, "Failed atomic moves are preferable to cache corruption.");
} finally {
// make sure to delete the temporary file in case the move failed
tmpFile.delete();
}
}
}
| 2,675 | 34.68 | 100 | java |
codeql | codeql-master/java/ql/src/Frameworks/Spring/Architecture/Refactoring Opportunities/UnusedBean.java | class Start {
public static void main(String[] args) {
// Create a context from the XML file, constructing beans
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml"});
// Retrieve the petStore from the context bean factory.
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// Use the value
List<String> userList = service.getUsernameList();
}
} | 435 | 35.333333 | 79 | java |
codeql | codeql-master/java/ql/src/Frameworks/Spring/Violations of Best Practice/UseSetterInjectionGood.java | // Class for bean 'chart2'
public class ChartMaker {
private AxisRenderer axisRenderer = new DefaultAxisRenderer();
private TrendRenderer trendRenderer = new DefaultTrendRenderer();
public ChartMaker() {}
public void setAxisRenderer(AxisRenderer axisRenderer) {
this.axisRenderer = axisRenderer;
}
public void setTrendRenderer(TrendRenderer trendRenderer) {
this.trendRenderer = trendRenderer;
}
} | 414 | 26.666667 | 66 | java |
codeql | codeql-master/java/ql/src/Frameworks/Spring/Violations of Best Practice/UseSetterInjection.java | // Class for bean 'chart1'
public class WrongChartMaker {
private AxisRenderer axisRenderer = new DefaultAxisRenderer();
private TrendRenderer trendRenderer = new DefaultTrendRenderer();
public WrongChartMaker() {}
// Each combination of the optional parameters must be represented by a constructor.
public WrongChartMaker(AxisRenderer customAxisRenderer) {
this.axisRenderer = customAxisRenderer;
}
public WrongChartMaker(TrendRenderer customTrendRenderer) {
this.trendRenderer = customTrendRenderer;
}
public WrongChartMaker(AxisRenderer customAxisRenderer,
TrendRenderer customTrendRenderer) {
this.axisRenderer = customAxisRenderer;
this.trendRenderer = customTrendRenderer;
}
} | 715 | 31.545455 | 85 | java |
codeql | codeql-master/java/ql/src/Frameworks/Spring/XML Configuration Errors/MissingSetters.java | // bean class
public class ContentService {
private TransactionHelper helper;
// This method does not match the property in the bean file.
public void setHelper(TransactionHelper helper) {
this.helper = helper;
}
}
| 222 | 21.3 | 61 | java |
codeql | codeql-master/java/ql/src/Advisory/Statements/TerminateIfElseIfWithElseGood.java | int score;
char grade;
// ...
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else { // GOOD: Terminating 'else' clause for all other scores
grade = 'F';
}
System.out.println("Grade = " + grade); | 321 | 17.941176 | 65 | java |
codeql | codeql-master/java/ql/src/Advisory/Statements/TerminateIfElseIfWithElse.java | int score;
char grade;
// ...
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
// BAD: No terminating 'else' clause
}
System.out.println("Grade = " + grade); | 277 | 16.375 | 39 | java |
codeql | codeql-master/java/ql/src/Advisory/Statements/MissingDefaultInSwitchGood.java | int menuChoice;
// ...
switch (menuChoice) {
case 1:
System.out.println("You chose number 1.");
break;
case 2:
System.out.println("You chose number 2.");
break;
case 3:
System.out.println("You chose number 3.");
break;
default: // GOOD: 'default' case for invalid choices
System.out.println("Sorry, you made an invalid choice.");
break;
} | 421 | 22.444444 | 65 | java |
codeql | codeql-master/java/ql/src/Advisory/Statements/MissingDefaultInSwitch.java | int menuChoice;
// ...
switch (menuChoice) {
case 1:
System.out.println("You chose number 1.");
break;
case 2:
System.out.println("You chose number 2.");
break;
case 3:
System.out.println("You chose number 3.");
break;
// BAD: No 'default' case
} | 312 | 18.5625 | 50 | java |
codeql | codeql-master/java/ql/src/Advisory/Types/Generics_Common.java | public List constructRawList(Object o) {
List list; // Raw variable declaration
list = new ArrayList(); // Raw constructor call
list.add(o);
return list; // Raw method return type (see signature above)
} | 222 | 36.166667 | 65 | java |
codeql | codeql-master/java/ql/src/Advisory/Types/Generics_CommonGood.java | public <T> List<T> constructParameterizedList(T o) {
List<T> list; // Parameterized variable declaration
list = new ArrayList<T>(); // Parameterized constructor call
list.add(o);
return list; // Parameterized method return type (see signature above)
} | 270 | 44.166667 | 75 | java |
codeql | codeql-master/java/ql/src/Advisory/Documentation/MissingJavadocMethods.java | /**
* Extracts the user's name from the input arguments.
*
* Precondition: 'args' should contain at least one element, the user's name.
*
* @param args the command-line arguments.
* @return the user's name (the first command-line argument).
* @throws NoNameException if 'args' contains no element.
*/
public static String getName(String[] args) throws NoNameException {
if(args.length == 0) {
throw new NoNameException();
} else {
return args[0];
}
} | 493 | 29.875 | 77 | java |
codeql | codeql-master/java/ql/src/Advisory/Documentation/MissingJavadocTypes.java | /**
* The Stack class represents a last-in-first-out stack of objects.
*
* @author Joseph Bergin
* @version 1.0, May 2000
* Note that this version is not thread safe.
*/
public class Stack {
// ... | 206 | 22 | 68 | java |
codeql | codeql-master/java/ql/src/Advisory/Documentation/ImpossibleJavadocThrowsFix.java | /**
* Javadoc for method.
*/
public void noThrow() {
System.out.println("This method does not throw.");
} | 108 | 17.166667 | 51 | java |
codeql | codeql-master/java/ql/src/Advisory/Documentation/SpuriousJavadocParam.java | /**
* BAD: The following param tag is empty.
*
* @param
*/
public void emptyParamTag(int p){ ... }
/**
* BAD: The following param tag has a misspelled value.
*
* @param prameter The parameter's value.
*/
public void typo(int parameter){ ... }
/**
* BAD: The following param tag appears to be outdated
* since the method does not take any parameters.
*
* @param sign The number's sign.
*/
public void outdated(){ ... }
/**
* BAD: The following param tag uses html within the tag value.
*
* @param <code>ordinate</code> The value of the y coordinate.
*/
public void html(int ordinate){ ... }
/**
* BAD: Invalid syntax for type parameter.
*
* @param T The type of the parameter.
* @param parameter The parameter value.
*/
public <T> void parameterized(T parameter){ ... }
/**
* GOOD: A proper Javadoc comment.
*
* This method calculates the absolute value of a given number.
*
* @param <T> The number's type.
* @param x The number to calculate the absolute value of.
* @return The absolute value of <code>x</code>.
*/
public <T extends Number> T abs(T x){ ... }
| 1,108 | 19.924528 | 63 | java |
codeql | codeql-master/java/ql/src/Advisory/Documentation/ImpossibleJavadocThrows.java | /**
* Javadoc for method.
*
* @throws Exception if a problem occurs.
*/
public void noThrow() {
System.out.println("This method does not throw.");
} | 153 | 18.25 | 51 | java |
codeql | codeql-master/java/ql/src/Advisory/Declarations/MissingOverrideAnnotation.java | class Rectangle
{
private int w = 10, h = 10;
public int getArea() {
return w * h;
}
}
class Triangle extends Rectangle
{
@Override // Annotation of an overriding method
public int getArea() {
return super.getArea() / 2;
}
} | 272 | 17.2 | 53 | java |
codeql | codeql-master/java/ql/src/Advisory/Java Objects/AvoidCloneableInterface.java | public final class Galaxy {
// This is the original constructor.
public Galaxy (double aMass, String aName) {
fMass = aMass;
fName = aName;
}
// This is the copy constructor.
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
}
// ...
} | 316 | 20.133333 | 51 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/CNumberOfParameters2.java | void printMembership(Set<Fellow> fellows, Set<Member> members,
Set<Associate> associates, Set<Student> students) {
for(Fellow f: fellows) {
System.out.println(f);
}
for(Member m: members) {
System.out.println(m);
}
for(Associate a: associates) {
System.out.println(a);
}
for(Student s: students) {
System.out.println(s);
}
}
void printRecords() {
//...
printMembership(fellows, members, associates, students);
} | 506 | 24.35 | 72 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/CNumberOfParameters1.java | void printAnnotation(String annotationMessage, int annotationLine, int annotationOffset,
int annotationLength) {
System.out.println("Message: " + annotationMessage);
System.out.println("Line: " + annotationLine);
System.out.println("Offset: " + annotationOffset);
System.out.println("Length: " + annotationLength); | 351 | 57.666667 | 88 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/CNumberOfParameters1Good.java | class Annotation {
//...
}
void printAnnotation(Annotation annotation) {
System.out.println("Message: " + annotation.getMessage());
System.out.println("Line: " + annotation.getLine());
System.out.println("Offset: " + annotation.getOffset());
System.out.println("Length: " + annotation.getLength());
} | 321 | 31.2 | 62 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/CNumberOfParameters2Good.java | void printFellows(Set<Fellow> fellows) {
for(Fellow f: fellows) {
System.out.println(f);
}
}
//...
void printRecords() {
//...
printFellows(fellows);
printMembers(members);
printAssociates(associates);
printStudents(students);
} | 266 | 16.8 | 40 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/CCyclomaticComplexity.java | int f(int i, int j) {
int result;
if(i % 2 == 0) {
result = i + j;
}
else {
if(j % 2 == 0) {
result = i * j;
}
else {
result = i - j;
}
}
return result;
} | 242 | 15.2 | 27 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/StatementNestingDepthGood.java | public static void printAllCharInts(String s) {
if (s != null) {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + "=" + (int) s.charAt(i));
}
}
}
public static void printCharacterCodes_Good(String[] strings) {
if (strings != null) {
for(String s : strings){
printAllCharInts(s);
}
}
} | 379 | 26.142857 | 70 | java |
codeql | codeql-master/java/ql/src/Metrics/Callables/StatementNestingDepth.java | public static void printCharacterCodes_Bad(String[] strings) {
if (strings != null) {
for (String s : strings) {
if (s != null) {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + "=" + (int) s.charAt(i));
}
}
}
}
} | 337 | 29.727273 | 78 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TSpecialisationIndex.java | abstract class Animal {
protected String animalName;
public Animal(String name) {
animalName = name;
}
public String getName(){
return animalName;
}
public abstract String getKind();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public String getName() { // This method duplicates the method in class 'Cat'.
return animalName + " the " + getKind();
}
public String getKind() {
return "dog";
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public String getName() { // This method duplicates the method in class 'Dog'.
return animalName + " the " + getKind();
}
public String getKind() {
return "cat";
}
}
| 802 | 18.585366 | 83 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TEfferentCouplingGood.java | class YX {
public void iUseY(Y y) {
y.doStuff();
}
public Y soDoY() {
return new Y();
}
}
class ZX {
public Z iUseZ(Z z1, Z z2) {
return z1.combine(z2);
}
} | 206 | 12.8 | 32 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TNumberOfFieldsGood.java | class Name {
private String m_firstName;
private String m_lastName;
// ...
}
class Address {
private int m_houseNumber;
private String m_street;
private String m_settlement;
private Country m_country;
private Postcode m_postcode;
// ...
}
class Person {
private Name m_name;
private Address m_address;
// ...
} | 360 | 17.05 | 32 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TEfferentCoupling.java | class X {
public void iUseY(Y y) {
y.doStuff();
}
public Y soDoY() {
return new Y();
}
public Z iUseZ(Z z1, Z z2) {
return z1.combine(z2);
}
} | 192 | 13.846154 | 32 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TSpecialisationIndexGood.java | abstract class Animal {
private String animalName;
public Animal(String name) {
animalName = name;
}
public String getName() { // Method has been pulled up into the base class.
return animalName + " the " + getKind();
}
public abstract String getKind();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public String getKind() {
return "dog";
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public String getKind() {
return "cat";
}
}
| 593 | 16.470588 | 80 | java |
codeql | codeql-master/java/ql/src/Metrics/RefTypes/TNumberOfFields.java | class Person {
private String m_firstName;
private String m_LastName;
private int m_houseNumber;
private String m_street;
private String m_settlement;
private Country m_country;
private Postcode m_postcode;
// ...
} | 247 | 23.8 | 32 | java |
codeql | codeql-master/java/ql/src/Metrics/Files/FCyclomaticComplexity.java | int f(int i, int j) {
// start
int result;
if(i % 2 == 0) {
// iEven
result = i + j;
}
else {
// iOdd
if(j % 2 == 0) {
// jEven
result = i * j;
}
else {
// jOdd
result = i - j;
}
}
return result;
// end
} | 340 | 15.238095 | 27 | java |
codeql | codeql-master/java/ql/src/external/DuplicateMethod.java | class RowWidget extends Widget {
// ...
public void collectChildren(Set<Widget> result) {
for (Widget child : this.children) {
if (child.isVisible()) {
result.add(children);
child.collectChildren(result);
}
}
}
}
class ColumnWidget extends Widget {
// ...
public void collectChildren(Set<Widget> result) {
for (Widget child : this.children) {
if (child.isVisible()) {
result.add(children);
child.collectChildren(result);
}
}
}
} | 471 | 19.521739 | 50 | java |
codeql | codeql-master/java/ql/src/external/DuplicateAnonymous.java | // BAD: Duplicate anonymous classes:
button1.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
for (ActionListener listener: listeners)
listeners.actionPerformed(e);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
for (ActionListener listener: listeners)
listeners.actionPerformed(e);
}
});
// ... and so on.
// GOOD: Better solution:
class MultiplexingListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
for (ActionListener listener : listeners)
listener.actionPerformed(e);
}
}
button1.addActionListener(new MultiplexingListener());
button2.addActionListener(new MultiplexingListener());
// ... and so on.
| 820 | 25.483871 | 54 | java |
codeql | codeql-master/java/ql/src/Performance/NewStringString.java | public void sayHello(String world) {
// AVOID: Inefficient 'String' constructor
String message = new String("hello ");
// AVOID: Inefficient 'String' constructor
message = new String(message + world);
// AVOID: Inefficient 'String' constructor
System.out.println(new String(message));
} | 294 | 28.5 | 43 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientOutputStreamGood.java | public class DigestCheckingFileOutputStream extends OutputStream {
private DigestOutputStream digest;
private byte[] expectedMD5;
public DigestCheckingFileOutputStream(File file, byte[] expectedMD5)
throws IOException, NoSuchAlgorithmException {
this.expectedMD5 = expectedMD5;
digest = new DigestOutputStream(new FileOutputStream(file),
MessageDigest.getInstance("MD5"));
}
@Override
public void write(int b) throws IOException {
digest.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
digest.write(b, off, len);
}
@Override
public void close() throws IOException {
super.close();
digest.close();
byte[] md5 = digest.getMessageDigest().digest();
if (expectedMD5 != null && !Arrays.equals(expectedMD5, md5)) {
throw new InternalError();
}
}
}
| 838 | 24.424242 | 69 | java |
codeql | codeql-master/java/ql/src/Performance/ConcatenationInLoops.java | public class ConcatenationInLoops {
public static void main(String[] args) {
Random r = new Random(123);
long start = System.currentTimeMillis();
String s = "";
for (int i = 0; i < 65536; i++)
s += r.nextInt(2);
System.out.println(System.currentTimeMillis() - start); // This prints roughly 4500.
r = new Random(123);
start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 65536; i++)
sb.append(r.nextInt(2));
s = sb.toString();
System.out.println(System.currentTimeMillis() - start); // This prints 5.
}
} | 580 | 31.277778 | 87 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientToArray.java | class Company {
private List<Customer> customers = ...;
public Customer[] getCustomerArray() {
// AVOID: Inefficient call to 'toArray' with zero-length argument
return customers.toArray(new Customer[0]);
}
}
class Company {
private List<Customer> customers = ...;
public Customer[] getCustomerArray() {
// GOOD: More efficient call to 'toArray' with argument that is big enough to store the list
return customers.toArray(new Customer[customers.size()]);
}
}
class Company {
private static final Customer[] NO_CUSTOMERS = new Customer[0];
private List<Customer> customers = ...;
public Customer[] getCustomerArray() {
// GOOD: Reuse same zero-length array on every invocation
return customers.toArray(NO_CUSTOMERS);
}
} | 749 | 25.785714 | 94 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientPrimConstructor.java | public class Account {
private Integer balance;
public Account(Integer startingBalance) {
this.balance = startingBalance;
}
}
public class BankManager {
public void openAccount(Customer c) {
...
// AVOID: Inefficient primitive constructor
accounts.add(new Account(new Integer(0)));
// GOOD: Use 'valueOf'
accounts.add(new Account(Integer.valueOf(0)));
// GOOD: Rely on autoboxing
accounts.add(new Account(0));
}
} | 435 | 23.222222 | 48 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientKeySetIterator.java | // AVOID: Iterate the map using the key set.
class AddressBook {
private Map<String, Person> people = ...;
public String findId(String first, String last) {
for (String id : people.keySet()) {
Person p = people.get(id);
if (first.equals(p.firstName()) && last.equals(p.lastName()))
return id;
}
return null;
}
}
// GOOD: Iterate the map using the entry set.
class AddressBook {
private Map<String, Person> people = ...;
public String findId(String first, String last) {
for (Entry<String, Person> entry: people.entrySet()) {
Person p = entry.getValue();
if (first.equals(p.firstName()) && last.equals(p.lastName()))
return entry.getKey();
}
return null;
}
} | 696 | 26.88 | 64 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientOutputStreamBad.java | public class DigestCheckingFileOutputStream extends OutputStream {
private DigestOutputStream digest;
private byte[] expectedMD5;
public DigestCheckingFileOutputStream(File file, byte[] expectedMD5)
throws IOException, NoSuchAlgorithmException {
this.expectedMD5 = expectedMD5;
digest = new DigestOutputStream(new FileOutputStream(file),
MessageDigest.getInstance("MD5"));
}
@Override
public void write(int b) throws IOException {
digest.write(b);
}
@Override
public void close() throws IOException {
super.close();
digest.close();
byte[] md5 = digest.getMessageDigest().digest();
if (expectedMD5 != null && !Arrays.equals(expectedMD5, md5)) {
throw new InternalError();
}
}
}
| 726 | 24.964286 | 69 | java |
codeql | codeql-master/java/ql/src/Performance/InefficientEmptyStringTest.java | // Inefficient version
class InefficientDBClient {
public void connect(String user, String pw) {
if (user.equals("") || "".equals(pw))
throw new RuntimeException();
...
}
}
// More efficient version
class EfficientDBClient {
public void connect(String user, String pw) {
if (user.length() == 0 || (pw != null && pw.length() == 0))
throw new RuntimeException();
...
}
}
| 388 | 20.611111 | 61 | java |
codeql | codeql-master/java/ql/src/Architecture/Dependencies/MutualDependencyFix.java | public class NoMutualDependency {
// Better: A new interface breaks the dependency
// from the model to the view
private interface ModelListener {
void modelChanged();
}
private static class BetterModel {
private int i;
private ModelListener listener;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
if (listener != null) listener.modelChanged();
}
public void setListener(ModelListener listener) {
this.listener = listener;
}
}
private static class BetterView implements ModelListener {
private BetterModel model;
public BetterView(BetterModel model) {
this.model = model;
}
public void modelChanged() {
System.out.println("Model Changed: " + model.getI());
}
}
public static void main(String[] args) {
BadModel badModel = new BadModel();
BadView badView = new BadView(badModel);
badModel.setView(badView);
badModel.setI(23);
badModel.setI(9);
BetterModel betterModel = new BetterModel();
BetterView betterView = new BetterView(betterModel);
betterModel.setListener(betterView);
betterModel.setI(24);
betterModel.setI(12);
}
} | 1,134 | 21.254902 | 59 | java |
codeql | codeql-master/java/ql/src/Architecture/Dependencies/MutualDependency.java | public class MutualDependency {
// Violation: BadModel and BadView are mutually dependent
private static class BadModel {
private int i;
private BadView view;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
if(view != null) view.modelChanged();
}
public void setView(BadView view) {
this.view = view;
}
}
private static class BadView {
private BadModel model;
public BadView(BadModel model) {
this.model = model;
}
public void modelChanged() {
System.out.println("Model Changed: " + model.getI());
}
}
} | 580 | 17.15625 | 58 | java |
codeql | codeql-master/java/ql/src/Architecture/Refactoring Opportunities/DeeplyNestedClass.java | class X1 {
private int i;
public X1(int i) {
this.i = i;
}
public Y1 makeY1(float j) {
return new Y1(j);
}
class Y1 {
private float j;
public Y1(float j) {
this.j = j;
}
public Z1 makeZ1(double k) {
return new Z1(k);
}
// Violation
class Z1 {
private double k;
public Z1(double k) {
this.k = k;
}
public void foo() {
System.out.println(i * j * k);
}
}
}
}
public class DeeplyNestedClass {
public static void main(String[] args) {
new X1(23).makeY1(9.0f).makeZ1(84.0).foo();
}
} | 545 | 12.317073 | 45 | java |
codeql | codeql-master/java/ql/src/Architecture/Refactoring Opportunities/DeeplyNestedClassFix.java | class X2 {
private int i;
public X2(int i) {
this.i = i;
}
public Y2 makeY2(float j) {
return new Y2(i, j);
}
}
class Y2 {
private int i;
private float j;
public Y2(int i, float j) {
this.i = i;
this.j = j;
}
public Z2 makeZ2(double k) {
return new Z2(i, j, k);
}
}
class Z2 {
private int i;
private float j;
private double k;
public Z2(int i, float j, double k) {
this.i = i;
this.j = j;
this.k = k;
}
public void foo() {
System.out.println(i * j * k);
}
}
public class NotNestedClass {
public static void main(String[] args) {
new X2(23).makeY2(9.0f).makeZ2(84.0).foo();
}
} | 625 | 12.319149 | 45 | java |
codeql | codeql-master/java/ql/src/Architecture/Refactoring Opportunities/FeatureEnvy.java | // Before refactoring:
class Item { .. }
class Basket {
// ..
float getTotalPrice(Item i) {
float price = i.getPrice() + i.getTax();
if (i.isOnSale())
price = price - i.getSaleDiscount() * price;
return price;
}
}
// After refactoring:
class Item {
// ..
float getTotalPrice() {
float price = getPrice() + getTax();
if (isOnSale())
price = price - getSaleDiscount() * price;
return price;
}
} | 417 | 18 | 47 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/CallsToSystemExit.java | // Problem 1: Miss out cleanup code
class FileOutput {
boolean write(String[] s) {
try {
output.write(s.getBytes());
} catch (IOException e) {
System.exit(1);
}
return true;
}
}
// Problem 2: Make code reuse difficult
class Action {
public void run() {
// ...
// Perform tasks ...
// ...
System.exit(0);
}
public static void main(String[] args) {
new Action(args).run();
}
} | 496 | 19.708333 | 44 | java |
codeql | codeql-master/java/ql/src/Violations of Best Practice/Undesirable Calls/GarbageCollection.java | class RequestHandler extends Thread {
private boolean isRunning;
private Connection conn = new Connection();
public void run() {
while (isRunning) {
Request req = conn.getRequest();
// Process the request ...
System.gc(); // This call may cause a garbage collection after each request.
// This will likely reduce the throughput of the RequestHandler
// because the JVM spends time on unnecessary garbage collection passes.
}
}
} | 468 | 30.266667 | 80 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.