Merge branch 'main' into flask-clean-models

This commit is contained in:
Rasmus Wriedt Larsen
2021-02-18 16:08:18 +01:00
440 changed files with 3680 additions and 1473 deletions

View File

@@ -49,7 +49,11 @@ If you have an idea for a query that you would like to share with other CodeQL u
- The query must have at least one true positive result on some revision of a real project.
Experimental queries and libraries may not be actively maintained as the [supported](docs/supported-queries.md) libraries evolve. They may also be changed in backwards-incompatible ways or may be removed entirely in the future without deprecation warnings.
6. **Query help files and unit tests**
- Query help (`.qhelp`) files and unit tests are optional (but strongly encouraged!) for queries in the `experimental` directories. For more information about contributing query help files and unit tests, see [Supported CodeQL queries and libraries](docs/supported-queries.md).
Experimental queries and libraries may not be actively maintained as the supported libraries evolve. They may also be changed in backwards-incompatible ways or may be removed entirely in the future without deprecation warnings.
After the experimental query is merged, we welcome pull requests to improve it. Before a query can be moved out of the `experimental` subdirectory, it must satisfy [the requirements for being a supported query](docs/supported-queries.md).

View File

@@ -15,7 +15,7 @@ import semmle.code.cpp.models.interfaces.Iterator
*/
private class IteratorTraits extends Class {
IteratorTraits() {
this.hasQualifiedName("std", "iterator_traits") and
this.hasQualifiedName(["std", "bsl"], "iterator_traits") and
not this instanceof TemplateClass and
exists(TypedefType t |
this.getAMember() = t and
@@ -26,6 +26,14 @@ private class IteratorTraits extends Class {
Type getIteratorType() { result = this.getTemplateArgument(0) }
}
/**
* A type that is deduced to be an iterator because there is a corresponding
* `std::iterator_traits` instantiation for it.
*/
private class IteratorByTraits extends Iterator {
IteratorByTraits() { exists(IteratorTraits it | it.getIteratorType() = this) }
}
/**
* A type which has the typedefs expected for an iterator.
*/
@@ -36,7 +44,7 @@ private class IteratorByTypedefs extends Iterator, Class {
this.getAMember().(TypedefType).hasName("pointer") and
this.getAMember().(TypedefType).hasName("reference") and
this.getAMember().(TypedefType).hasName("iterator_category") and
not this.hasQualifiedName("std", "iterator_traits")
not this.hasQualifiedName(["std", "bsl"], "iterator_traits")
}
}
@@ -44,17 +52,13 @@ private class IteratorByTypedefs extends Iterator, Class {
* The `std::iterator` class.
*/
private class StdIterator extends Iterator, Class {
StdIterator() { this.hasQualifiedName("std", "iterator") }
StdIterator() { this.hasQualifiedName(["std", "bsl"], "iterator") }
}
/**
* A type that is deduced to be an iterator because there is a corresponding
* `std::iterator_traits` instantiation for it.
* Gets the `FunctionInput` corresponding to an iterator parameter to
* user-defined operator `op`, at `index`.
*/
private class IteratorByTraits extends Iterator {
IteratorByTraits() { exists(IteratorTraits it | it.getIteratorType() = this) }
}
private FunctionInput getIteratorArgumentInput(Operator op, int index) {
exists(Type t |
t =
@@ -155,17 +159,21 @@ private class IteratorSubOperator extends Operator, TaintFunction {
private class IteratorAssignArithmeticOperator extends Operator, DataFlowFunction, TaintFunction {
IteratorAssignArithmeticOperator() {
this.hasName(["operator+=", "operator-="]) and
this.getDeclaringType() instanceof Iterator
exists(getIteratorArgumentInput(this, 0))
}
override predicate hasDataFlow(FunctionInput input, FunctionOutput output) {
input.isParameter(0) and
output.isReturnValue()
or
input.isParameterDeref(0) and output.isReturnValueDeref()
}
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
input.isParameterDeref(0) and output.isReturnValueDeref()
or
// reverse flow from returned reference to the object referenced by the first parameter
input.isReturnValueDeref() and
output.isParameterDeref(0)
or
input.isParameterDeref(1) and
output.isParameterDeref(0)
}
@@ -177,8 +185,7 @@ private class IteratorAssignArithmeticOperator extends Operator, DataFlowFunctio
class IteratorPointerDereferenceMemberOperator extends MemberFunction, TaintFunction,
IteratorReferenceFunction {
IteratorPointerDereferenceMemberOperator() {
this.hasName("operator*") and
this.getDeclaringType() instanceof Iterator
this.getClassAndName("operator*") instanceof Iterator
}
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
@@ -195,8 +202,7 @@ class IteratorPointerDereferenceMemberOperator extends MemberFunction, TaintFunc
*/
private class IteratorCrementMemberOperator extends MemberFunction, DataFlowFunction, TaintFunction {
IteratorCrementMemberOperator() {
this.hasName(["operator++", "operator--"]) and
this.getDeclaringType() instanceof Iterator
this.getClassAndName(["operator++", "operator--"]) instanceof Iterator
}
override predicate hasDataFlow(FunctionInput input, FunctionOutput output) {
@@ -220,10 +226,7 @@ private class IteratorCrementMemberOperator extends MemberFunction, DataFlowFunc
* A member `operator->` function for an iterator type.
*/
private class IteratorFieldMemberOperator extends Operator, TaintFunction {
IteratorFieldMemberOperator() {
this.hasName("operator->") and
this.getDeclaringType() instanceof Iterator
}
IteratorFieldMemberOperator() { this.getClassAndName("operator->") instanceof Iterator }
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
input.isQualifierObject() and
@@ -236,8 +239,7 @@ private class IteratorFieldMemberOperator extends Operator, TaintFunction {
*/
private class IteratorBinaryArithmeticMemberOperator extends MemberFunction, TaintFunction {
IteratorBinaryArithmeticMemberOperator() {
this.hasName(["operator+", "operator-"]) and
this.getDeclaringType() instanceof Iterator
this.getClassAndName(["operator+", "operator-"]) instanceof Iterator
}
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
@@ -252,21 +254,24 @@ private class IteratorBinaryArithmeticMemberOperator extends MemberFunction, Tai
private class IteratorAssignArithmeticMemberOperator extends MemberFunction, DataFlowFunction,
TaintFunction {
IteratorAssignArithmeticMemberOperator() {
this.hasName(["operator+=", "operator-="]) and
this.getDeclaringType() instanceof Iterator
this.getClassAndName(["operator+=", "operator-="]) instanceof Iterator
}
override predicate hasDataFlow(FunctionInput input, FunctionOutput output) {
input.isQualifierAddress() and
output.isReturnValue()
or
input.isReturnValueDeref() and
output.isQualifierObject()
}
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
input.isQualifierObject() and
output.isReturnValueDeref()
or
// reverse flow from returned reference to the qualifier
input.isReturnValueDeref() and
output.isQualifierObject()
or
input.isParameterDeref(0) and
output.isQualifierObject()
}
}
@@ -275,10 +280,7 @@ private class IteratorAssignArithmeticMemberOperator extends MemberFunction, Dat
*/
private class IteratorArrayMemberOperator extends MemberFunction, TaintFunction,
IteratorReferenceFunction {
IteratorArrayMemberOperator() {
this.hasName("operator[]") and
this.getDeclaringType() instanceof Iterator
}
IteratorArrayMemberOperator() { this.getClassAndName("operator[]") instanceof Iterator }
override predicate hasTaintFlow(FunctionInput input, FunctionOutput output) {
input.isQualifierObject() and
@@ -295,8 +297,7 @@ private class IteratorArrayMemberOperator extends MemberFunction, TaintFunction,
*/
private class IteratorAssignmentMemberOperator extends MemberFunction, TaintFunction {
IteratorAssignmentMemberOperator() {
this.hasName("operator=") and
this.getDeclaringType() instanceof Iterator and
this.getClassAndName("operator=") instanceof Iterator and
not this instanceof CopyAssignmentOperator and
not this instanceof MoveAssignmentOperator
}
@@ -337,7 +338,7 @@ private class BeginOrEndFunction extends MemberFunction, TaintFunction, GetItera
*/
private class InserterIteratorFunction extends GetIteratorFunction {
InserterIteratorFunction() {
this.hasQualifiedName("std", ["front_inserter", "inserter", "back_inserter"])
this.hasQualifiedName(["std", "bsl"], ["front_inserter", "inserter", "back_inserter"])
}
override predicate getsIterator(FunctionInput input, FunctionOutput output) {

View File

@@ -1,6 +1,6 @@
# C/C++ CodeQL tests
This document provides additional information about the C/C++ CodeQL Tests located in `cpp/ql/test`. See [Contributing to CodeQL](/CONTRIBUTING.md) for general information about contributing to this repository.
This document provides additional information about the C/C++ CodeQL tests located in `cpp/ql/test`. The principles under "Copying code", below, also apply to any other C/C++ code in this repository, such as examples linked from query `.qhelp` files in `cpp/ql/src`. For more general information about contributing to this repository, see [Contributing to CodeQL](/CONTRIBUTING.md).
The tests can be run through Visual Studio Code. Advanced users may also use the `codeql test run` command.

View File

@@ -3197,6 +3197,56 @@
| standalone_iterators.cpp:90:8:90:8 | call to operator-- | standalone_iterators.cpp:90:5:90:5 | call to operator* | TAINT |
| standalone_iterators.cpp:90:8:90:8 | ref arg call to operator-- | standalone_iterators.cpp:90:6:90:7 | ref arg i2 | |
| standalone_iterators.cpp:90:13:90:13 | 0 | standalone_iterators.cpp:90:5:90:5 | ref arg call to operator* | TAINT |
| standalone_iterators.cpp:98:15:98:16 | call to container | standalone_iterators.cpp:101:6:101:7 | c1 | |
| standalone_iterators.cpp:98:15:98:16 | call to container | standalone_iterators.cpp:102:6:102:7 | c1 | |
| standalone_iterators.cpp:98:15:98:16 | call to container | standalone_iterators.cpp:106:6:106:7 | c1 | |
| standalone_iterators.cpp:98:15:98:16 | call to container | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:101:6:101:7 | c1 | standalone_iterators.cpp:101:9:101:13 | call to begin | TAINT |
| standalone_iterators.cpp:101:6:101:7 | ref arg c1 | standalone_iterators.cpp:102:6:102:7 | c1 | |
| standalone_iterators.cpp:101:6:101:7 | ref arg c1 | standalone_iterators.cpp:106:6:106:7 | c1 | |
| standalone_iterators.cpp:101:6:101:7 | ref arg c1 | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:101:9:101:13 | call to begin | standalone_iterators.cpp:101:2:101:15 | ... = ... | |
| standalone_iterators.cpp:101:9:101:13 | call to begin | standalone_iterators.cpp:103:3:103:3 | a | |
| standalone_iterators.cpp:101:9:101:13 | call to begin | standalone_iterators.cpp:104:7:104:7 | a | |
| standalone_iterators.cpp:102:6:102:7 | c1 | standalone_iterators.cpp:102:9:102:13 | call to begin | TAINT |
| standalone_iterators.cpp:102:6:102:7 | ref arg c1 | standalone_iterators.cpp:106:6:106:7 | c1 | |
| standalone_iterators.cpp:102:6:102:7 | ref arg c1 | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:102:9:102:13 | call to begin | standalone_iterators.cpp:102:2:102:15 | ... = ... | |
| standalone_iterators.cpp:102:9:102:13 | call to begin | standalone_iterators.cpp:107:7:107:7 | b | |
| standalone_iterators.cpp:103:2:103:2 | ref arg call to operator* | standalone_iterators.cpp:103:3:103:3 | ref arg a | TAINT |
| standalone_iterators.cpp:103:2:103:2 | ref arg call to operator* | standalone_iterators.cpp:106:6:106:7 | c1 | |
| standalone_iterators.cpp:103:2:103:2 | ref arg call to operator* | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:103:3:103:3 | a | standalone_iterators.cpp:103:2:103:2 | call to operator* | TAINT |
| standalone_iterators.cpp:103:3:103:3 | ref arg a | standalone_iterators.cpp:104:7:104:7 | a | |
| standalone_iterators.cpp:103:7:103:12 | call to source | standalone_iterators.cpp:103:2:103:2 | ref arg call to operator* | TAINT |
| standalone_iterators.cpp:104:7:104:7 | a [post update] | standalone_iterators.cpp:106:6:106:7 | c1 | |
| standalone_iterators.cpp:104:7:104:7 | a [post update] | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:106:6:106:7 | c1 | standalone_iterators.cpp:106:9:106:13 | call to begin | TAINT |
| standalone_iterators.cpp:106:6:106:7 | ref arg c1 | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:106:9:106:13 | call to begin | standalone_iterators.cpp:106:2:106:15 | ... = ... | |
| standalone_iterators.cpp:106:9:106:13 | call to begin | standalone_iterators.cpp:108:7:108:7 | c | |
| standalone_iterators.cpp:107:7:107:7 | b [post update] | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:108:7:108:7 | c [post update] | standalone_iterators.cpp:109:7:109:8 | c1 | |
| standalone_iterators.cpp:113:15:113:16 | call to container | standalone_iterators.cpp:116:7:116:8 | c1 | |
| standalone_iterators.cpp:113:15:113:16 | call to container | standalone_iterators.cpp:122:7:122:8 | c1 | |
| standalone_iterators.cpp:116:7:116:8 | c1 | standalone_iterators.cpp:116:10:116:14 | call to begin | TAINT |
| standalone_iterators.cpp:116:7:116:8 | ref arg c1 | standalone_iterators.cpp:122:7:122:8 | c1 | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:116:2:116:16 | ... = ... | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:117:7:117:8 | it | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:118:2:118:3 | it | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:119:7:119:8 | it | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:120:2:120:3 | it | |
| standalone_iterators.cpp:116:10:116:14 | call to begin | standalone_iterators.cpp:121:7:121:8 | it | |
| standalone_iterators.cpp:117:7:117:8 | it [post update] | standalone_iterators.cpp:122:7:122:8 | c1 | |
| standalone_iterators.cpp:118:2:118:3 | it | standalone_iterators.cpp:118:5:118:5 | call to operator+= | |
| standalone_iterators.cpp:118:2:118:3 | ref arg it | standalone_iterators.cpp:119:7:119:8 | it | |
| standalone_iterators.cpp:118:2:118:3 | ref arg it | standalone_iterators.cpp:120:2:120:3 | it | |
| standalone_iterators.cpp:118:2:118:3 | ref arg it | standalone_iterators.cpp:121:7:121:8 | it | |
| standalone_iterators.cpp:118:2:118:3 | ref arg it | standalone_iterators.cpp:122:7:122:8 | c1 | |
| standalone_iterators.cpp:118:8:118:8 | 1 | standalone_iterators.cpp:118:2:118:3 | ref arg it | TAINT |
| standalone_iterators.cpp:120:2:120:3 | it | standalone_iterators.cpp:120:5:120:5 | call to operator+= | |
| standalone_iterators.cpp:120:2:120:3 | ref arg it | standalone_iterators.cpp:121:7:121:8 | it | |
| standalone_iterators.cpp:120:8:120:13 | call to source | standalone_iterators.cpp:120:2:120:3 | ref arg it | TAINT |
| stl.h:75:8:75:8 | Unknown literal | stl.h:75:8:75:8 | constructor init of field container | TAINT |
| stl.h:75:8:75:8 | Unknown literal | stl.h:75:8:75:8 | constructor init of field container | TAINT |
| stl.h:75:8:75:8 | this | stl.h:75:8:75:8 | constructor init of field container [pre-this] | |
@@ -3876,12 +3926,12 @@
| string.cpp:408:8:408:9 | i2 | string.cpp:409:10:409:11 | i7 | |
| string.cpp:409:10:409:11 | i7 | string.cpp:409:12:409:12 | call to operator+= | |
| string.cpp:409:12:409:12 | call to operator+= | string.cpp:409:8:409:8 | call to operator* | TAINT |
| string.cpp:409:14:409:14 | 1 | string.cpp:409:12:409:12 | call to operator+= | |
| string.cpp:409:14:409:14 | 1 | string.cpp:409:10:409:11 | ref arg i7 | TAINT |
| string.cpp:410:8:410:9 | i2 | string.cpp:410:3:410:9 | ... = ... | |
| string.cpp:410:8:410:9 | i2 | string.cpp:411:10:411:11 | i8 | |
| string.cpp:411:10:411:11 | i8 | string.cpp:411:12:411:12 | call to operator-= | |
| string.cpp:411:12:411:12 | call to operator-= | string.cpp:411:8:411:8 | call to operator* | TAINT |
| string.cpp:411:14:411:14 | 1 | string.cpp:411:12:411:12 | call to operator-= | |
| string.cpp:411:14:411:14 | 1 | string.cpp:411:10:411:11 | ref arg i8 | TAINT |
| string.cpp:413:8:413:9 | s2 | string.cpp:413:11:413:13 | call to end | TAINT |
| string.cpp:413:11:413:13 | call to end | string.cpp:413:3:413:15 | ... = ... | |
| string.cpp:413:11:413:13 | call to end | string.cpp:414:5:414:6 | i9 | |
@@ -7496,3 +7546,64 @@
| vector.cpp:496:25:496:30 | call to source | vector.cpp:496:2:496:3 | ref arg v2 | TAINT |
| vector.cpp:496:25:496:30 | call to source | vector.cpp:496:5:496:11 | call to emplace | TAINT |
| vector.cpp:497:7:497:8 | ref arg v2 | vector.cpp:498:1:498:1 | v2 | |
| vector.cpp:503:18:503:21 | {...} | vector.cpp:506:8:506:9 | as | |
| vector.cpp:503:18:503:21 | {...} | vector.cpp:507:8:507:9 | as | |
| vector.cpp:503:18:503:21 | {...} | vector.cpp:509:9:509:10 | as | |
| vector.cpp:503:18:503:21 | {...} | vector.cpp:515:8:515:9 | as | |
| vector.cpp:503:20:503:20 | 0 | vector.cpp:503:18:503:21 | {...} | TAINT |
| vector.cpp:506:8:506:9 | as | vector.cpp:506:8:506:12 | access to array | |
| vector.cpp:506:11:506:11 | 1 | vector.cpp:506:8:506:12 | access to array | TAINT |
| vector.cpp:507:8:507:9 | as | vector.cpp:507:8:507:19 | access to array | |
| vector.cpp:507:11:507:16 | call to source | vector.cpp:507:8:507:19 | access to array | TAINT |
| vector.cpp:509:9:509:10 | as | vector.cpp:509:3:509:10 | ... = ... | |
| vector.cpp:509:9:509:10 | as | vector.cpp:510:9:510:11 | ptr | |
| vector.cpp:509:9:509:10 | as | vector.cpp:511:3:511:5 | ptr | |
| vector.cpp:510:9:510:11 | ptr | vector.cpp:510:8:510:11 | * ... | TAINT |
| vector.cpp:511:3:511:5 | ptr | vector.cpp:511:3:511:10 | ... += ... | TAINT |
| vector.cpp:511:3:511:10 | ... += ... | vector.cpp:512:9:512:11 | ptr | |
| vector.cpp:511:3:511:10 | ... += ... | vector.cpp:513:3:513:5 | ptr | |
| vector.cpp:511:10:511:10 | 1 | vector.cpp:511:3:511:10 | ... += ... | TAINT |
| vector.cpp:512:9:512:11 | ptr | vector.cpp:512:8:512:11 | * ... | TAINT |
| vector.cpp:513:3:513:5 | ptr | vector.cpp:513:3:513:17 | ... += ... | TAINT |
| vector.cpp:513:3:513:17 | ... += ... | vector.cpp:514:9:514:11 | ptr | |
| vector.cpp:513:10:513:15 | call to source | vector.cpp:513:3:513:17 | ... += ... | TAINT |
| vector.cpp:514:9:514:11 | ptr | vector.cpp:514:8:514:11 | * ... | TAINT |
| vector.cpp:515:8:515:9 | as | vector.cpp:515:8:515:12 | access to array | |
| vector.cpp:515:11:515:11 | 1 | vector.cpp:515:8:515:12 | access to array | TAINT |
| vector.cpp:520:25:520:31 | call to vector | vector.cpp:523:8:523:9 | vs | |
| vector.cpp:520:25:520:31 | call to vector | vector.cpp:524:8:524:9 | vs | |
| vector.cpp:520:25:520:31 | call to vector | vector.cpp:526:8:526:9 | vs | |
| vector.cpp:520:25:520:31 | call to vector | vector.cpp:532:8:532:9 | vs | |
| vector.cpp:520:25:520:31 | call to vector | vector.cpp:533:2:533:2 | vs | |
| vector.cpp:520:30:520:30 | 0 | vector.cpp:520:25:520:31 | call to vector | TAINT |
| vector.cpp:523:8:523:9 | ref arg vs | vector.cpp:524:8:524:9 | vs | |
| vector.cpp:523:8:523:9 | ref arg vs | vector.cpp:526:8:526:9 | vs | |
| vector.cpp:523:8:523:9 | ref arg vs | vector.cpp:532:8:532:9 | vs | |
| vector.cpp:523:8:523:9 | ref arg vs | vector.cpp:533:2:533:2 | vs | |
| vector.cpp:523:8:523:9 | vs | vector.cpp:523:10:523:10 | call to operator[] | TAINT |
| vector.cpp:524:8:524:9 | ref arg vs | vector.cpp:526:8:526:9 | vs | |
| vector.cpp:524:8:524:9 | ref arg vs | vector.cpp:532:8:532:9 | vs | |
| vector.cpp:524:8:524:9 | ref arg vs | vector.cpp:533:2:533:2 | vs | |
| vector.cpp:524:8:524:9 | vs | vector.cpp:524:10:524:10 | call to operator[] | TAINT |
| vector.cpp:526:8:526:9 | ref arg vs | vector.cpp:532:8:532:9 | vs | |
| vector.cpp:526:8:526:9 | ref arg vs | vector.cpp:533:2:533:2 | vs | |
| vector.cpp:526:8:526:9 | vs | vector.cpp:526:11:526:15 | call to begin | TAINT |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:526:3:526:17 | ... = ... | |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:527:9:527:10 | it | |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:528:3:528:4 | it | |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:529:9:529:10 | it | |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:530:3:530:4 | it | |
| vector.cpp:526:11:526:15 | call to begin | vector.cpp:531:9:531:10 | it | |
| vector.cpp:527:9:527:10 | it | vector.cpp:527:8:527:8 | call to operator* | TAINT |
| vector.cpp:528:3:528:4 | it | vector.cpp:528:6:528:6 | call to operator+= | |
| vector.cpp:528:3:528:4 | ref arg it | vector.cpp:529:9:529:10 | it | |
| vector.cpp:528:3:528:4 | ref arg it | vector.cpp:530:3:530:4 | it | |
| vector.cpp:528:3:528:4 | ref arg it | vector.cpp:531:9:531:10 | it | |
| vector.cpp:528:9:528:9 | 1 | vector.cpp:528:3:528:4 | ref arg it | TAINT |
| vector.cpp:529:9:529:10 | it | vector.cpp:529:8:529:8 | call to operator* | TAINT |
| vector.cpp:530:3:530:4 | it | vector.cpp:530:6:530:6 | call to operator+= | |
| vector.cpp:530:3:530:4 | ref arg it | vector.cpp:531:9:531:10 | it | |
| vector.cpp:530:9:530:14 | call to source | vector.cpp:530:3:530:4 | ref arg it | TAINT |
| vector.cpp:531:9:531:10 | it | vector.cpp:531:8:531:8 | call to operator* | TAINT |
| vector.cpp:532:8:532:9 | ref arg vs | vector.cpp:533:2:533:2 | vs | |
| vector.cpp:532:8:532:9 | vs | vector.cpp:532:10:532:10 | call to operator[] | TAINT |

View File

@@ -90,3 +90,34 @@ void test_insert_iterator() {
*i2-- = 0;
sink(c2); // clean
}
void sink(insert_iterator_by_trait);
insert_iterator_by_trait &operator+=(insert_iterator_by_trait &it, int amount);
void test_assign_through_iterator() {
container c1;
insert_iterator_by_trait a, b, c;
a = c1.begin();
b = c1.begin();
*a = source();
sink(a); // $ ast MISSING: ir
c = c1.begin();
sink(b); // MISSING: ast,ir
sink(c); // $ ast MISSING: ir
sink(c1); // $ ast MISSING: ir
}
void test_nonmember_iterator() {
container c1;
insert_iterator_by_trait it;
it = c1.begin();
sink(it);
it += 1;
sink(it);
it += source();
sink(it); // $ ast,ir
sink(c1);
}

View File

@@ -496,3 +496,39 @@ void test_vector_emplace() {
v2.emplace(v2.begin(), source());
sink(v2); // $ ast,ir
}
void test_vector_iterator() {
{
// array behaviour, for comparison
short as[100] = {0};
short *ptr;
sink(as[1]);
sink(as[source()]); // $ ast,ir
ptr = as;
sink(*ptr);
ptr += 1;
sink(*ptr);
ptr += source();
sink(*ptr); // $ ast,ir
sink(as[1]);
}
{
// iterator behaviour
std::vector<short> vs(100, 0);
std::vector<short>::iterator it;
sink(vs[1]);
sink(vs[source()]); // $ MISSING: ast,ir
it = vs.begin();
sink(*it);
it += 1;
sink(*it);
it += source();
sink(*it); // $ ast,ir
sink(vs[1]);
}
}

View File

@@ -95,11 +95,11 @@ namespace Semmle.Extraction.CIL
/// <param name="h">The handle of the entity.</param>
/// <param name="genericContext">The generic context.</param>
/// <returns></returns>
public IExtractedEntity CreateGeneric(GenericContext genericContext, Handle h) => genericHandleFactory[genericContext, h];
public IExtractedEntity CreateGeneric(IGenericContext genericContext, Handle h) => genericHandleFactory[genericContext, h];
private readonly GenericContext defaultGenericContext;
private readonly IGenericContext defaultGenericContext;
private IExtractedEntity CreateGenericHandle(GenericContext gc, Handle handle)
private IExtractedEntity CreateGenericHandle(IGenericContext gc, Handle handle)
{
IExtractedEntity entity;
switch (handle.Kind)
@@ -136,7 +136,7 @@ namespace Semmle.Extraction.CIL
return entity;
}
private IExtractedEntity Create(GenericContext gc, MemberReferenceHandle handle)
private IExtractedEntity Create(IGenericContext gc, MemberReferenceHandle handle)
{
var mr = MdReader.GetMemberReference(handle);
switch (mr.GetKind())
@@ -228,7 +228,7 @@ namespace Semmle.Extraction.CIL
#endregion
private readonly CachedFunction<GenericContext, Handle, IExtractedEntity> genericHandleFactory;
private readonly CachedFunction<IGenericContext, Handle, IExtractedEntity> genericHandleFactory;
/// <summary>
/// Gets the short name of a member, without the preceding interface qualifier.

View File

@@ -37,7 +37,7 @@ namespace Semmle.Extraction.CIL
globalNamespace = new Lazy<Entities.Namespace>(() => Populate(new Entities.Namespace(this, "", null)));
systemNamespace = new Lazy<Entities.Namespace>(() => Populate(new Entities.Namespace(this, "System")));
genericHandleFactory = new CachedFunction<GenericContext, Handle, IExtractedEntity>(CreateGenericHandle);
genericHandleFactory = new CachedFunction<IGenericContext, Handle, IExtractedEntity>(CreateGenericHandle);
namespaceFactory = new CachedFunction<StringHandle, Entities.Namespace>(n => CreateNamespace(MdReader.GetString(n)));
namespaceDefinitionFactory = new CachedFunction<NamespaceDefinitionHandle, Entities.Namespace>(CreateNamespace);
sourceFiles = new CachedFunction<PDB.ISourceFile, Entities.PdbSourceFile>(path => new Entities.PdbSourceFile(this, path));

View File

@@ -5,14 +5,18 @@ namespace Semmle.Extraction.CIL
/// <summary>
/// A generic context which does not contain any type parameters.
/// </summary>
public class EmptyContext : GenericContext
public class EmptyContext : IGenericContext
{
public EmptyContext(Context cx) : base(cx)
public EmptyContext(Context cx)
{
Cx = cx;
}
public override IEnumerable<Entities.Type> TypeParameters { get { yield break; } }
public Context Cx { get; }
public IEnumerable<Entities.Type> TypeParameters { get { yield break; } }
public IEnumerable<Entities.Type> MethodParameters { get { yield break; } }
public override IEnumerable<Entities.Type> MethodParameters { get { yield break; } }
}
}

View File

@@ -40,6 +40,7 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write(FullName);
trapFile.Write("#file:///");
trapFile.Write(Cx.AssemblyPath.Replace("\\", "/"));
trapFile.Write(";assembly");
}
public override bool Equals(object? obj)
@@ -49,8 +50,6 @@ namespace Semmle.Extraction.CIL.Entities
public override int GetHashCode() => 7 * file.GetHashCode();
public override string IdSuffix => ";assembly";
private string FullName => assemblyName.GetPublicKey() is null ? assemblyName.FullName + ", PublicKeyToken=null" : assemblyName.FullName;
public override IEnumerable<IExtractionProduct> Contents

View File

@@ -12,9 +12,9 @@ namespace Semmle.Extraction.CIL.Entities
{
private readonly CustomAttributeHandle handle;
private readonly CustomAttribute attrib;
private readonly IEntity @object;
private readonly IExtractedEntity @object;
public Attribute(Context cx, IEntity @object, CustomAttributeHandle handle) : base(cx)
public Attribute(Context cx, IExtractedEntity @object, CustomAttributeHandle handle) : base(cx)
{
attrib = cx.MdReader.GetCustomAttribute(handle);
this.handle = handle;
@@ -80,7 +80,7 @@ namespace Semmle.Extraction.CIL.Entities
return value?.ToString() ?? "null";
}
public static IEnumerable<IExtractionProduct> Populate(Context cx, IEntity @object, CustomAttributeHandleCollection attributes)
public static IEnumerable<IExtractionProduct> Populate(Context cx, IExtractedEntity @object, CustomAttributeHandleCollection attributes)
{
foreach (var attrib in attributes)
{

View File

@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// A CIL entity which has been extracted.
/// </summary>
public interface IExtractedEntity : IExtractionProduct, IEntity
{
/// <summary>
/// The contents of the entity.
/// </summary>
IEnumerable<IExtractionProduct> Contents { get; }
}
}

View File

@@ -0,0 +1,24 @@
namespace Semmle.Extraction.CIL
{
/// <summary>
/// Something that is extracted from an entity.
/// </summary>
///
/// <remarks>
/// The extraction algorithm proceeds as follows:
/// - Construct entity
/// - Call Extract()
/// - IExtractedEntity check if already extracted
/// - Enumerate Contents to produce more extraction products
/// - Extract these until there is nothing left to extract
/// </remarks>
public interface IExtractionProduct
{
/// <summary>
/// Perform further extraction/population of this item as necessary.
/// </summary>
///
/// <param name="cx">The extraction context.</param>
void Extract(Context cx);
}
}

View File

@@ -0,0 +1,24 @@
using System.Collections.Generic;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// When we decode a type/method signature, we need access to
/// generic parameters.
/// </summary>
public interface IGenericContext
{
Context Cx { get; }
/// <summary>
/// The list of generic type parameters/arguments, including type parameters/arguments of
/// containing types.
/// </summary>
IEnumerable<Entities.Type> TypeParameters { get; }
/// <summary>
/// The list of generic method parameters/arguments.
/// </summary>
IEnumerable<Entities.Type> MethodParameters { get; }
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// An entity that needs to be populated during extraction.
/// This assigns a key and optionally extracts its contents.
/// </summary>
public abstract class LabelledEntity : Extraction.LabelledEntity, IExtractedEntity
{
// todo: with .NET 5 this can override the base context, and change the return type.
public Context Cx { get; }
protected LabelledEntity(Context cx) : base(cx.Cx)
{
this.Cx = cx;
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public void Extract(Context cx2)
{
cx2.Populate(this);
}
public override string ToString()
{
using var writer = new StringWriter();
WriteQuotedId(writer);
return writer.ToString();
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<IExtractionProduct> Contents { get; }
}
}

View File

@@ -0,0 +1,22 @@
namespace Semmle.Extraction.CIL
{
/// <summary>
/// A tuple that is an extraction product.
/// </summary>
internal class Tuple : IExtractionProduct
{
private readonly Extraction.Tuple tuple;
public Tuple(string name, params object[] args)
{
tuple = new Extraction.Tuple(name, args);
}
public void Extract(Context cx)
{
cx.Cx.Emit(tuple);
}
public override string ToString() => tuple.ToString();
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// An entity that has contents to extract. There is no need to populate
/// a key as it's done in the contructor.
/// </summary>
public abstract class UnlabelledEntity : Extraction.UnlabelledEntity, IExtractedEntity
{
// todo: with .NET 5 this can override the base context, and change the return type.
public Context Cx { get; }
protected UnlabelledEntity(Context cx) : base(cx.Cx)
{
Cx = cx;
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public void Extract(Context cx2)
{
cx2.Extract(this);
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<IExtractionProduct> Contents { get; }
}
}

View File

@@ -23,7 +23,7 @@ namespace Semmle.Extraction.CIL.Entities
public override IList<LocalVariable>? LocalVariables => locals;
public DefinitionMethod(GenericContext gc, MethodDefinitionHandle handle) : base(gc)
public DefinitionMethod(IGenericContext gc, MethodDefinitionHandle handle) : base(gc)
{
md = Cx.MdReader.GetMethodDefinition(handle);
this.gc = gc;

View File

@@ -25,10 +25,9 @@ namespace Semmle.Extraction.CIL.Entities
parent.WriteId(trapFile);
trapFile.Write('.');
trapFile.Write(Cx.ShortName(ed.Name));
trapFile.Write(";cil-event");
}
public override string IdSuffix => ";cil-event";
public override bool Equals(object? obj)
{
return obj is Event e && handle.Equals(e.handle);

View File

@@ -7,13 +7,13 @@ namespace Semmle.Extraction.CIL.Entities
/// </summary>
internal class ExceptionRegion : UnlabelledEntity
{
private readonly GenericContext gc;
private readonly IGenericContext gc;
private readonly MethodImplementation method;
private readonly int index;
private readonly System.Reflection.Metadata.ExceptionRegion r;
private readonly Dictionary<int, Instruction> jump_table;
public ExceptionRegion(GenericContext gc, MethodImplementation method, int index, System.Reflection.Metadata.ExceptionRegion r, Dictionary<int, Instruction> jump_table) : base(gc.Cx)
public ExceptionRegion(IGenericContext gc, MethodImplementation method, int index, System.Reflection.Metadata.ExceptionRegion r, Dictionary<int, Instruction> jump_table) : base(gc.Cx)
{
this.gc = gc;
this.method = method;

View File

@@ -8,40 +8,27 @@ namespace Semmle.Extraction.CIL.Entities
/// <summary>
/// An entity representing a field.
/// </summary>
internal abstract class Field : GenericContext, IMember, ICustomModifierReceiver
internal abstract class Field : LabelledEntity, IGenericContext, IMember, ICustomModifierReceiver
{
protected Field(Context cx) : base(cx)
{
}
public Label Label { get; set; }
public void WriteId(TextWriter trapFile)
public override void WriteId(TextWriter trapFile)
{
trapFile.WriteSubId(DeclaringType);
trapFile.Write('.');
trapFile.Write(Name);
trapFile.Write(";cil-field");
}
public void WriteQuotedId(TextWriter trapFile)
{
trapFile.Write("@\"");
WriteId(trapFile);
trapFile.Write(idSuffix);
trapFile.Write('\"');
}
private const string idSuffix = ";cil-field";
public abstract string Name { get; }
public abstract Type DeclaringType { get; }
public Location ReportingLocation => throw new NotImplementedException();
public abstract Type Type { get; }
public virtual IEnumerable<IExtractionProduct> Contents
public override IEnumerable<IExtractionProduct> Contents
{
get
{
@@ -55,11 +42,8 @@ namespace Semmle.Extraction.CIL.Entities
}
}
public void Extract(Context cx2)
{
cx2.Populate(this);
}
public abstract IEnumerable<Type> TypeParameters { get; }
TrapStackBehaviour IEntity.TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<Type> MethodParameters { get; }
}
}

View File

@@ -17,6 +17,7 @@ namespace Semmle.Extraction.CIL.Entities
public override void WriteId(TextWriter trapFile)
{
trapFile.Write(TransformedPath.DatabaseId);
trapFile.Write(";sourcefile");
}
public override bool Equals(object? obj)
@@ -39,7 +40,5 @@ namespace Semmle.Extraction.CIL.Entities
yield return Tuples.files(this, TransformedPath.Value, TransformedPath.NameWithoutExtension, TransformedPath.Extension);
}
}
public override string IdSuffix => ";sourcefile";
}
}

View File

@@ -15,10 +15,9 @@ namespace Semmle.Extraction.CIL.Entities
public override void WriteId(TextWriter trapFile)
{
trapFile.Write(transformedPath.DatabaseId);
trapFile.Write(";folder");
}
public override string IdSuffix => ";folder";
public override IEnumerable<IExtractionProduct> Contents
{
get

View File

@@ -4,6 +4,6 @@ namespace Semmle.Extraction.CIL.Entities
{
internal interface ITypeSignature
{
void WriteId(TextWriter trapFile, GenericContext gc);
void WriteId(TextWriter trapFile, IGenericContext gc);
}
}

View File

@@ -8,7 +8,7 @@ namespace Semmle.Extraction.CIL.Entities
/// <summary>
/// A CIL instruction.
/// </summary>
internal class Instruction : UnlabelledEntity, IEntity
internal class Instruction : UnlabelledEntity
{
/// <summary>
/// The additional data following the opcode, if any.
@@ -289,11 +289,6 @@ namespace Semmle.Extraction.CIL.Entities
}
}
Label IEntity.Label
{
get; set;
}
private readonly byte[] data;
private int PayloadSize => payloadSizes[(int)PayloadType];

View File

@@ -21,10 +21,9 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.WriteSubId(method);
trapFile.Write('_');
trapFile.Write(index);
trapFile.Write(";cil-local");
}
public override string IdSuffix => ";cil-local";
public override IEnumerable<IExtractionProduct> Contents
{
get

View File

@@ -8,10 +8,10 @@ namespace Semmle.Extraction.CIL.Entities
{
private readonly MemberReferenceHandle handle;
private readonly MemberReference mr;
private readonly GenericContext gc;
private readonly IGenericContext gc;
private readonly Type declType;
public MemberReferenceField(GenericContext gc, MemberReferenceHandle handle) : base(gc.Cx)
public MemberReferenceField(IGenericContext gc, MemberReferenceHandle handle) : base(gc.Cx)
{
this.handle = handle;
this.gc = gc;

View File

@@ -12,10 +12,10 @@ namespace Semmle.Extraction.CIL.Entities
private readonly MemberReferenceHandle handle;
private readonly MemberReference mr;
private readonly Type declaringType;
private readonly GenericContext parent;
private readonly IGenericContext parent;
private readonly Method? sourceDeclaration;
public MemberReferenceMethod(GenericContext gc, MemberReferenceHandle handle) : base(gc)
public MemberReferenceMethod(IGenericContext gc, MemberReferenceHandle handle) : base(gc)
{
this.handle = handle;
this.gc = gc;
@@ -23,7 +23,7 @@ namespace Semmle.Extraction.CIL.Entities
signature = mr.DecodeMethodSignature(new SignatureDecoder(), gc);
parent = (GenericContext)Cx.CreateGeneric(gc, mr.Parent);
parent = (IGenericContext)Cx.CreateGeneric(gc, mr.Parent);
var declType = parent is Method parentMethod
? parentMethod.DeclaringType

View File

@@ -12,10 +12,10 @@ namespace Semmle.Extraction.CIL.Entities
internal abstract class Method : TypeContainer, IMember, ICustomModifierReceiver, IParameterizable
{
protected MethodTypeParameter[]? genericParams;
protected GenericContext gc;
protected IGenericContext gc;
protected MethodSignature<ITypeSignature> signature;
protected Method(GenericContext gc) : base(gc.Cx)
protected Method(IGenericContext gc) : base(gc.Cx)
{
this.gc = gc;
}

View File

@@ -18,7 +18,7 @@ namespace Semmle.Extraction.CIL.Entities
private readonly Method unboundMethod;
private readonly ImmutableArray<Type> typeParams;
public MethodSpecificationMethod(GenericContext gc, MethodSpecificationHandle handle) : base(gc)
public MethodSpecificationMethod(IGenericContext gc, MethodSpecificationHandle handle) : base(gc)
{
this.handle = handle;
ms = Cx.MdReader.GetMethodSpecification(handle);

View File

@@ -21,7 +21,7 @@ namespace Semmle.Extraction.CIL.Entities
public override string Name => "!" + index;
public MethodTypeParameter(GenericContext gc, Method m, int index) : base(gc)
public MethodTypeParameter(IGenericContext gc, Method m, int index) : base(gc)
{
method = m;
this.index = index;

View File

@@ -14,9 +14,6 @@ namespace Semmle.Extraction.CIL.Entities
public bool IsGlobalNamespace => ParentNamespace is null;
public override string IdSuffix => ";namespace";
public override void WriteId(TextWriter trapFile)
{
if (ParentNamespace != null && !ParentNamespace.IsGlobalNamespace)
@@ -27,6 +24,8 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write(Name);
}
public override string IdSuffix => ";namespacee";
public override bool Equals(object? obj)
{
if (obj is Namespace ns && Name == ns.Name)

View File

@@ -8,41 +8,40 @@ namespace Semmle.Extraction.CIL.Entities
/// </summary>
internal sealed class Parameter : LabelledEntity
{
private readonly IParameterizable method;
private readonly IParameterizable parameterizable;
private readonly int index;
private readonly Type type;
public Parameter(Context cx, IParameterizable m, int i, Type t) : base(cx)
public Parameter(Context cx, IParameterizable p, int i, Type t) : base(cx)
{
method = m;
parameterizable = p;
index = i;
type = t;
}
public override void WriteId(TextWriter trapFile)
{
trapFile.WriteSubId(method);
trapFile.WriteSubId(parameterizable);
trapFile.Write('_');
trapFile.Write(index);
trapFile.Write(";cil-parameter");
}
public override bool Equals(object? obj)
{
return obj is Parameter param && method.Equals(param.method) && index == param.index;
return obj is Parameter param && parameterizable.Equals(param.parameterizable) && index == param.index;
}
public override int GetHashCode()
{
return 23 * method.GetHashCode() + index;
return 23 * parameterizable.GetHashCode() + index;
}
public override string IdSuffix => ";cil-parameter";
public override IEnumerable<IExtractionProduct> Contents
{
get
{
yield return Tuples.cil_parameter(this, method, index, type);
yield return Tuples.cil_parameter(this, parameterizable, index, type);
}
}
}

View File

@@ -13,10 +13,9 @@ namespace Semmle.Extraction.CIL.Entities
private readonly Handle handle;
private readonly Type type;
private readonly PropertyDefinition pd;
public override string IdSuffix => ";cil-property";
private readonly GenericContext gc;
private readonly IGenericContext gc;
public Property(GenericContext gc, Type type, PropertyDefinitionHandle handle) : base(gc.Cx)
public Property(IGenericContext gc, Type type, PropertyDefinitionHandle handle) : base(gc.Cx)
{
this.gc = gc;
this.handle = handle;
@@ -38,6 +37,7 @@ namespace Semmle.Extraction.CIL.Entities
param.WriteId(trapFile, gc);
}
trapFile.Write(")");
trapFile.Write(";cil-property");
}
public override bool Equals(object? obj)

View File

@@ -17,7 +17,7 @@ namespace Semmle.Extraction.CIL.Entities
this.shape = shape;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
elementType.WriteId(trapFile, gc);
trapFile.Write('[');
@@ -38,7 +38,7 @@ namespace Semmle.Extraction.CIL.Entities
this.elementType = elementType;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
elementType.WriteId(trapFile, gc);
trapFile.Write('&');
@@ -54,7 +54,7 @@ namespace Semmle.Extraction.CIL.Entities
this.signature = signature;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
FunctionPointerType.WriteName(
trapFile.Write,
@@ -84,7 +84,7 @@ namespace Semmle.Extraction.CIL.Entities
this.typeArguments = typeArguments;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
genericType.WriteId(trapFile, gc);
trapFile.Write('<');
@@ -112,7 +112,7 @@ namespace Semmle.Extraction.CIL.Entities
this.index = index;
}
public void WriteId(TextWriter trapFile, GenericContext outerGc)
public void WriteId(TextWriter trapFile, IGenericContext outerGc)
{
if (!ReferenceEquals(innerGc, outerGc) && innerGc is Method method)
{
@@ -132,7 +132,7 @@ namespace Semmle.Extraction.CIL.Entities
this.index = index;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
trapFile.Write("T!");
trapFile.Write(index);
@@ -158,7 +158,7 @@ namespace Semmle.Extraction.CIL.Entities
this.isRequired = isRequired;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
unmodifiedType.WriteId(trapFile, gc);
trapFile.Write(isRequired ? " modreq(" : " modopt(");
@@ -186,7 +186,7 @@ namespace Semmle.Extraction.CIL.Entities
this.elementType = elementType;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
elementType.WriteId(trapFile, gc);
trapFile.Write('*');
@@ -207,7 +207,7 @@ namespace Semmle.Extraction.CIL.Entities
this.typeCode = typeCode;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
trapFile.Write(typeCode.Id());
}
@@ -227,7 +227,7 @@ namespace Semmle.Extraction.CIL.Entities
this.elementType = elementType;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
elementType.WriteId(trapFile, gc);
trapFile.Write("[]");
@@ -248,7 +248,7 @@ namespace Semmle.Extraction.CIL.Entities
this.handle = handle;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
var type = (Type)gc.Cx.Create(handle);
type.WriteId(trapFile);
@@ -269,7 +269,7 @@ namespace Semmle.Extraction.CIL.Entities
this.handle = handle;
}
public void WriteId(TextWriter trapFile, GenericContext gc)
public void WriteId(TextWriter trapFile, IGenericContext gc)
{
var type = (Type)gc.Cx.Create(handle);
type.WriteId(trapFile);

View File

@@ -26,6 +26,7 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write(location.EndLine);
trapFile.Write(',');
trapFile.Write(location.EndColumn);
trapFile.Write(";sourcelocation");
}
public override bool Equals(object? obj)
@@ -43,7 +44,5 @@ namespace Semmle.Extraction.CIL.Entities
yield return Tuples.locations_default(this, file, location.StartLine, location.StartColumn, location.EndLine, location.EndColumn);
}
}
public override string IdSuffix => ";sourcelocation";
}
}

View File

@@ -11,7 +11,6 @@ namespace Semmle.Extraction.CIL.Entities
/// </summary>
public abstract class Type : TypeContainer, IMember
{
public override string IdSuffix => ";cil-type";
internal const string AssemblyTypeNameSeparator = "::";
internal const string PrimitiveTypePrefix = "builtin" + AssemblyTypeNameSeparator + "System.";
@@ -48,6 +47,8 @@ namespace Semmle.Extraction.CIL.Entities
public sealed override void WriteId(TextWriter trapFile) => WriteId(trapFile, false);
public override string IdSuffix => ";cil-type";
/// <summary>
/// Returns the friendly qualified name of types, such as
/// ``"System.Collection.Generic.List`1"`` or
@@ -198,7 +199,7 @@ namespace Semmle.Extraction.CIL.Entities
public sealed override IEnumerable<Type> MethodParameters => Enumerable.Empty<Type>();
public static Type DecodeType(GenericContext gc, TypeSpecificationHandle handle) =>
public static Type DecodeType(IGenericContext gc, TypeSpecificationHandle handle) =>
gc.Cx.MdReader.GetTypeSpecification(handle).DecodeSignature(gc.Cx.TypeSignatureDecoder, gc);
}
}

View File

@@ -1,5 +1,3 @@
using System;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
using System.IO;
@@ -8,17 +6,15 @@ namespace Semmle.Extraction.CIL.Entities
/// <summary>
/// Base class for all type containers (namespaces, types, methods).
/// </summary>
public abstract class TypeContainer : GenericContext, IExtractedEntity
public abstract class TypeContainer : LabelledEntity, IGenericContext
{
protected TypeContainer(Context cx) : base(cx)
{
}
public virtual Label Label { get; set; }
public abstract string IdSuffix { get; }
public abstract void WriteId(TextWriter trapFile);
public void WriteQuotedId(TextWriter trapFile)
public override void WriteQuotedId(TextWriter trapFile)
{
trapFile.Write("@\"");
WriteId(trapFile);
@@ -26,21 +22,7 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write('\"');
}
public abstract string IdSuffix { get; }
Location IEntity.ReportingLocation => throw new NotImplementedException();
public void Extract(Context cx2) { cx2.Populate(this); }
public abstract IEnumerable<IExtractionProduct> Contents { get; }
public override string ToString()
{
using var writer = new StringWriter();
WriteQuotedId(writer);
return writer.ToString();
}
TrapStackBehaviour IEntity.TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<Type> MethodParameters { get; }
public abstract IEnumerable<Type> TypeParameters { get; }
}
}

View File

@@ -9,9 +9,9 @@ namespace Semmle.Extraction.CIL.Entities
{
internal abstract class TypeParameter : Type
{
protected readonly GenericContext gc;
protected readonly IGenericContext gc;
protected TypeParameter(GenericContext gc) : base(gc.Cx)
protected TypeParameter(IGenericContext gc) : base(gc.Cx)
{
this.gc = gc;
}

View File

@@ -1,13 +1,14 @@
using System;
using System.Reflection.Metadata;
using System.Collections.Immutable;
using System.Linq;
namespace Semmle.Extraction.CIL.Entities
{
/// <summary>
/// Decodes a type signature and produces a Type, for use by DecodeSignature() and friends.
/// </summary>
public class TypeSignatureDecoder : ISignatureTypeProvider<Type, GenericContext>
public class TypeSignatureDecoder : ISignatureTypeProvider<Type, IGenericContext>
{
private readonly Context cx;
@@ -22,22 +23,22 @@ namespace Semmle.Extraction.CIL.Entities
Type IConstructedTypeProvider<Type>.GetByReferenceType(Type elementType) =>
new ByRefType(cx, elementType);
Type ISignatureTypeProvider<Type, GenericContext>.GetFunctionPointerType(MethodSignature<Type> signature) =>
Type ISignatureTypeProvider<Type, IGenericContext>.GetFunctionPointerType(MethodSignature<Type> signature) =>
cx.Populate(new FunctionPointerType(cx, signature));
Type IConstructedTypeProvider<Type>.GetGenericInstantiation(Type genericType, ImmutableArray<Type> typeArguments) =>
genericType.Construct(typeArguments);
Type ISignatureTypeProvider<Type, GenericContext>.GetGenericMethodParameter(GenericContext genericContext, int index) =>
genericContext.GetGenericMethodParameter(index);
Type ISignatureTypeProvider<Type, IGenericContext>.GetGenericMethodParameter(IGenericContext genericContext, int index) =>
genericContext.MethodParameters.ElementAt(index);
Type ISignatureTypeProvider<Type, GenericContext>.GetGenericTypeParameter(GenericContext genericContext, int index) =>
genericContext.GetGenericTypeParameter(index);
Type ISignatureTypeProvider<Type, IGenericContext>.GetGenericTypeParameter(IGenericContext genericContext, int index) =>
genericContext.TypeParameters.ElementAt(index);
Type ISignatureTypeProvider<Type, GenericContext>.GetModifiedType(Type modifier, Type unmodifiedType, bool isRequired) =>
Type ISignatureTypeProvider<Type, IGenericContext>.GetModifiedType(Type modifier, Type unmodifiedType, bool isRequired) =>
new ModifiedType(cx, unmodifiedType, modifier, isRequired);
Type ISignatureTypeProvider<Type, GenericContext>.GetPinnedType(Type elementType) => elementType;
Type ISignatureTypeProvider<Type, IGenericContext>.GetPinnedType(Type elementType) => elementType;
Type IConstructedTypeProvider<Type>.GetPointerType(Type elementType) =>
cx.Populate(new PointerType(cx, elementType));
@@ -53,7 +54,7 @@ namespace Semmle.Extraction.CIL.Entities
Type ISimpleTypeProvider<Type>.GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) =>
(Type)cx.Create(handle);
Type ISignatureTypeProvider<Type, GenericContext>.GetTypeFromSpecification(MetadataReader reader, GenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) =>
Type ISignatureTypeProvider<Type, IGenericContext>.GetTypeFromSpecification(MetadataReader reader, IGenericContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) =>
throw new NotImplementedException();
}
}

View File

@@ -1,140 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// Something that is extracted from an entity.
/// </summary>
///
/// <remarks>
/// The extraction algorithm proceeds as follows:
/// - Construct entity
/// - Call Extract()
/// - IExtractedEntity check if already extracted
/// - Enumerate Contents to produce more extraction products
/// - Extract these until there is nothing left to extract
/// </remarks>
public interface IExtractionProduct
{
/// <summary>
/// Perform further extraction/population of this item as necessary.
/// </summary>
///
/// <param name="cx">The extraction context.</param>
void Extract(Context cx);
}
/// <summary>
/// An entity which has been extracted.
/// </summary>
public interface IExtractedEntity : IEntity, IExtractionProduct
{
/// <summary>
/// The contents of the entity.
/// </summary>
IEnumerable<IExtractionProduct> Contents { get; }
}
/// <summary>
/// An entity that has contents to extract. There is no need to populate
/// a key as it's done in the contructor.
/// </summary>
public abstract class UnlabelledEntity : IExtractedEntity
{
public abstract IEnumerable<IExtractionProduct> Contents { get; }
public Label Label { get; set; }
public void WriteId(System.IO.TextWriter trapFile)
{
trapFile.Write('*');
}
public void WriteQuotedId(TextWriter trapFile)
{
WriteId(trapFile);
}
public Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public virtual void Extract(Context cx2)
{
cx2.Extract(this);
}
public Context Cx { get; }
protected UnlabelledEntity(Context cx)
{
this.Cx = cx;
cx.Cx.AddFreshLabel(this);
}
TrapStackBehaviour IEntity.TrapStackBehaviour => TrapStackBehaviour.NoLabel;
}
/// <summary>
/// An entity that needs to be populated during extraction.
/// This assigns a key and optionally extracts its contents.
/// </summary>
public abstract class LabelledEntity : IExtractedEntity
{
public abstract IEnumerable<IExtractionProduct> Contents { get; }
public Label Label { get; set; }
public Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public abstract void WriteId(System.IO.TextWriter trapFile);
public abstract string IdSuffix { get; }
public void WriteQuotedId(TextWriter trapFile)
{
trapFile.Write("@\"");
WriteId(trapFile);
trapFile.Write(IdSuffix);
trapFile.Write('\"');
}
public void Extract(Context cx2)
{
cx2.Populate(this);
}
public Context Cx { get; }
protected LabelledEntity(Context cx)
{
this.Cx = cx;
}
public override string ToString()
{
using var writer = new StringWriter();
WriteQuotedId(writer);
return writer.ToString();
}
TrapStackBehaviour IEntity.TrapStackBehaviour => TrapStackBehaviour.NoLabel;
}
/// <summary>
/// A tuple that is an extraction product.
/// </summary>
internal class Tuple : IExtractionProduct
{
private readonly Extraction.Tuple tuple;
public Tuple(string name, params object[] args)
{
tuple = new Extraction.Tuple(name, args);
}
public void Extract(Context cx)
{
cx.Cx.Emit(tuple);
}
public override string ToString() => tuple.ToString();
}
}

View File

@@ -1,56 +0,0 @@
using System.Collections.Generic;
using System.Linq;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// When we decode a type/method signature, we need access to
/// generic parameters.
/// </summary>
public abstract class GenericContext
{
public Context Cx { get; }
protected GenericContext(Context cx)
{
this.Cx = cx;
}
/// <summary>
/// The list of generic type parameters/arguments, including type parameters/arguments of
/// containing types.
/// </summary>
public abstract IEnumerable<Entities.Type> TypeParameters { get; }
/// <summary>
/// The list of generic method parameters.
/// </summary>
public abstract IEnumerable<Entities.Type> MethodParameters { get; }
/// <summary>
/// Gets the `p`th type parameter.
/// </summary>
/// <param name="p">The index of the parameter.</param>
/// <returns>
/// For constructed types, the supplied type.
/// For unbound types, the type parameter.
/// </returns>
public Entities.Type GetGenericTypeParameter(int p)
{
return TypeParameters.ElementAt(p);
}
/// <summary>
/// Gets the `p`th method type parameter.
/// </summary>
/// <param name="p">The index of the parameter.</param>
/// <returns>
/// For constructed types, the supplied type.
/// For unbound types, the type parameter.
/// </returns>
public Entities.Type GetGenericMethodParameter(int p)
{
return MethodParameters.ElementAt(p);
}
}
}

View File

@@ -14,10 +14,10 @@ namespace Semmle.Extraction.CIL
internal static Tuple cil_adder(Event member, Method method) =>
new Tuple("cil_adder", member, method);
internal static Tuple cil_access(Instruction i, IEntity m) =>
internal static Tuple cil_access(Instruction i, IExtractedEntity m) =>
new Tuple("cil_access", i, m);
internal static Tuple cil_attribute(Attribute attribute, IEntity @object, Method constructor) =>
internal static Tuple cil_attribute(Attribute attribute, IExtractedEntity @object, Method constructor) =>
new Tuple("cil_attribute", attribute, @object, constructor);
internal static Tuple cil_attribute_named_argument(Attribute attribute, string name, string value) =>
@@ -197,7 +197,7 @@ namespace Semmle.Extraction.CIL
internal static Tuple cil_custom_modifiers(ICustomModifierReceiver receiver, Type modifier, bool isRequired) =>
new Tuple("cil_custom_modifiers", receiver, modifier, isRequired ? 1 : 0);
internal static Tuple cil_type_annotation(IEntity receiver, TypeAnnotation annotation) =>
internal static Tuple cil_type_annotation(IExtractedEntity receiver, TypeAnnotation annotation) =>
new Tuple("cil_type_annotation", receiver, (int)annotation);
internal static Tuple containerparent(Folder parent, IFileOrFolder child) =>
@@ -215,7 +215,7 @@ namespace Semmle.Extraction.CIL
internal static Tuple locations_default(PdbSourceLocation label, File file, int startLine, int startCol, int endLine, int endCol) =>
new Tuple("locations_default", label, file, startLine, startCol, endLine, endCol);
internal static Tuple metadata_handle(IEntity entity, Assembly assembly, int handleValue) =>
internal static Tuple metadata_handle(IExtractedEntity entity, Assembly assembly, int handleValue) =>
new Tuple("metadata_handle", entity, assembly, handleValue);
internal static Tuple namespaces(Namespace ns, string name) =>

View File

@@ -29,9 +29,9 @@ namespace Semmle.Extraction.CSharp.Entities
/// <summary>
/// Gets the property symbol associated with this accessor.
/// </summary>
private IPropertySymbol PropertySymbol => GetPropertySymbol(symbol);
private IPropertySymbol PropertySymbol => GetPropertySymbol(Symbol);
public new Accessor OriginalDefinition => Create(Context, symbol.OriginalDefinition);
public new Accessor OriginalDefinition => Create(Context, Symbol.OriginalDefinition);
public override void Populate(TextWriter trapFile)
{
@@ -42,42 +42,42 @@ namespace Semmle.Extraction.CSharp.Entities
var prop = PropertySymbol;
if (prop == null)
{
Context.ModelError(symbol, "Unhandled accessor associated symbol");
Context.ModelError(Symbol, "Unhandled accessor associated symbol");
return;
}
var parent = Property.Create(Context, prop);
int kind;
Accessor unboundAccessor;
if (SymbolEqualityComparer.Default.Equals(symbol, prop.GetMethod))
if (SymbolEqualityComparer.Default.Equals(Symbol, prop.GetMethod))
{
kind = 1;
unboundAccessor = Create(Context, prop.OriginalDefinition.GetMethod);
}
else if (SymbolEqualityComparer.Default.Equals(symbol, prop.SetMethod))
else if (SymbolEqualityComparer.Default.Equals(Symbol, prop.SetMethod))
{
kind = 2;
unboundAccessor = Create(Context, prop.OriginalDefinition.SetMethod);
}
else
{
Context.ModelError(symbol, "Unhandled accessor kind");
Context.ModelError(Symbol, "Unhandled accessor kind");
return;
}
trapFile.accessors(this, kind, symbol.Name, parent, unboundAccessor);
trapFile.accessors(this, kind, Symbol.Name, parent, unboundAccessor);
foreach (var l in Locations)
trapFile.accessor_location(this, l);
Overrides(trapFile);
if (symbol.FromSource() && Block == null)
if (Symbol.FromSource() && Block == null)
{
trapFile.compiler_generated(this);
}
if (symbol.IsInitOnly)
if (Symbol.IsInitOnly)
{
trapFile.init_only_accessors(this);
}

View File

@@ -47,7 +47,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override void Populate(TextWriter trapFile)
{
var type = Type.Create(Context, symbol.AttributeClass);
var type = Type.Create(Context, Symbol.AttributeClass);
trapFile.attributes(this, type.TypeRef, entity);
trapFile.attribute_location(this, Location);
@@ -69,10 +69,10 @@ namespace Semmle.Extraction.CSharp.Entities
var ctorArguments = attributeSyntax?.ArgumentList?.Arguments.Where(a => a.NameEquals == null).ToList();
var childIndex = 0;
for (var i = 0; i < symbol.ConstructorArguments.Length; i++)
for (var i = 0; i < Symbol.ConstructorArguments.Length; i++)
{
var constructorArgument = symbol.ConstructorArguments[i];
var paramName = symbol.AttributeConstructor?.Parameters[i].Name;
var constructorArgument = Symbol.ConstructorArguments[i];
var paramName = Symbol.AttributeConstructor?.Parameters[i].Name;
var argSyntax = ctorArguments?.SingleOrDefault(a => a.NameColon != null && a.NameColon.Name.Identifier.Text == paramName);
if (argSyntax == null && // couldn't find named argument
@@ -89,7 +89,7 @@ namespace Semmle.Extraction.CSharp.Entities
childIndex++);
}
foreach (var namedArgument in symbol.NamedArguments)
foreach (var namedArgument in Symbol.NamedArguments)
{
var expr = CreateExpressionFromArgument(
namedArgument.Value,

View File

@@ -13,8 +13,8 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.commentblock(this);
var child = 0;
trapFile.commentblock_location(this, Context.CreateLocation(symbol.Location));
foreach (var l in symbol.CommentLines)
trapFile.commentblock_location(this, Context.CreateLocation(Symbol.Location));
foreach (var l in Symbol.CommentLines)
{
trapFile.commentblock_child(this, (CommentLine)l, child++);
}
@@ -24,11 +24,11 @@ namespace Semmle.Extraction.CSharp.Entities
public override void WriteId(TextWriter trapFile)
{
trapFile.WriteSubId(Context.CreateLocation(symbol.Location));
trapFile.WriteSubId(Context.CreateLocation(Symbol.Location));
trapFile.Write(";commentblock");
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => symbol.Location;
public override Microsoft.CodeAnalysis.Location ReportingLocation => Symbol.Location;
public void BindTo(Label entity, CommentBinding binding)
{

View File

@@ -13,10 +13,10 @@ namespace Semmle.Extraction.CSharp.Entities
RawText = raw;
}
public Microsoft.CodeAnalysis.Location Location => symbol.Item1;
public Microsoft.CodeAnalysis.Location Location => Symbol.Item1;
public CommentLineType Type { get; private set; }
public string Text { get { return symbol.Item2; } }
public string Text { get { return Symbol.Item2; } }
public string RawText { get; private set; }
private Location location;
@@ -28,7 +28,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.commentline_location(this, location);
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => location.symbol;
public override Microsoft.CodeAnalysis.Location ReportingLocation => location.Symbol;
public override bool NeedsPopulation => true;

View File

@@ -17,7 +17,7 @@ namespace Semmle.Extraction.CSharp.Entities
protected override void Populate(TextWriter trapFile)
{
trapFile.diagnostics(this, (int)diagnostic.Severity, diagnostic.Id, diagnostic.Descriptor.Title.ToString(),
diagnostic.GetMessage(), cx.CreateLocation(diagnostic.Location));
diagnostic.GetMessage(), Context.CreateLocation(diagnostic.Location));
}
}
}

View File

@@ -19,10 +19,10 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateModifiers(trapFile);
ContainingType.PopulateGenerics();
trapFile.constructors(this, symbol.ContainingType.Name, ContainingType, (Constructor)OriginalDefinition);
trapFile.constructors(this, Symbol.ContainingType.Name, ContainingType, (Constructor)OriginalDefinition);
trapFile.constructor_location(this, Location);
if (symbol.IsImplicitlyDeclared)
if (Symbol.IsImplicitlyDeclared)
{
var lineCounts = new LineCounts() { Total = 2, Code = 1, Comment = 0 };
trapFile.numlines(this, lineCounts);
@@ -48,10 +48,10 @@ namespace Semmle.Extraction.CSharp.Entities
switch (initializer.Kind())
{
case SyntaxKind.BaseConstructorInitializer:
initializerType = symbol.ContainingType.BaseType;
initializerType = Symbol.ContainingType.BaseType;
break;
case SyntaxKind.ThisConstructorInitializer:
initializerType = symbol.ContainingType;
initializerType = Symbol.ContainingType;
break;
default:
Context.ModelError(initializer, "Unknown initializer");
@@ -73,7 +73,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (target == null)
{
Context.ModelError(symbol, "Unable to resolve call");
Context.ModelError(Symbol, "Unable to resolve call");
return;
}
@@ -90,7 +90,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
get
{
return symbol.DeclaringSyntaxReferences
return Symbol.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.OfType<ConstructorDeclarationSyntax>()
.FirstOrDefault();
@@ -114,15 +114,15 @@ namespace Semmle.Extraction.CSharp.Entities
public override void WriteId(TextWriter trapFile)
{
if (symbol.IsStatic)
if (Symbol.IsStatic)
trapFile.Write("static");
trapFile.WriteSubId(ContainingType);
AddParametersToId(Context, trapFile, symbol);
AddParametersToId(Context, trapFile, Symbol);
trapFile.Write(";constructor");
}
private ConstructorDeclarationSyntax GetSyntax() =>
symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<ConstructorDeclarationSyntax>().FirstOrDefault();
Symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<ConstructorDeclarationSyntax>().FirstOrDefault();
public override Microsoft.CodeAnalysis.Location FullLocation => ReportingLocation;
@@ -136,12 +136,12 @@ namespace Semmle.Extraction.CSharp.Entities
return syn.Identifier.GetLocation();
}
if (symbol.IsImplicitlyDeclared)
if (Symbol.IsImplicitlyDeclared)
{
return ContainingType.ReportingLocation;
}
return symbol.ContainingType.Locations.FirstOrDefault();
return Symbol.ContainingType.Locations.FirstOrDefault();
}
}

View File

@@ -17,11 +17,11 @@ namespace Semmle.Extraction.CSharp.Entities
{
get
{
return symbol.DeclaringSyntaxReferences
return Symbol.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.OfType<ConversionOperatorDeclarationSyntax>()
.Select(s => s.FixedLocation())
.Concat(symbol.Locations)
.Concat(Symbol.Locations)
.FirstOrDefault();
}
}

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateModifiers(trapFile);
ContainingType.PopulateGenerics();
trapFile.destructors(this, string.Format("~{0}", symbol.ContainingType.Name), ContainingType, OriginalDefinition(Context, this, symbol));
trapFile.destructors(this, string.Format("~{0}", Symbol.ContainingType.Name), ContainingType, OriginalDefinition(Context, this, Symbol));
trapFile.destructor_location(this, Location);
}

View File

@@ -14,20 +14,20 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.WriteSubId(ContainingType);
trapFile.Write('.');
Method.AddExplicitInterfaceQualifierToId(Context, trapFile, symbol.ExplicitInterfaceImplementations);
trapFile.Write(symbol.Name);
Method.AddExplicitInterfaceQualifierToId(Context, trapFile, Symbol.ExplicitInterfaceImplementations);
trapFile.Write(Symbol.Name);
trapFile.Write(";event");
}
public override void Populate(TextWriter trapFile)
{
PopulateNullability(trapFile, symbol.GetAnnotatedType());
PopulateNullability(trapFile, Symbol.GetAnnotatedType());
var type = Type.Create(Context, symbol.Type);
trapFile.events(this, symbol.GetName(), ContainingType, type.TypeRef, Create(Context, symbol.OriginalDefinition));
var type = Type.Create(Context, Symbol.Type);
trapFile.events(this, Symbol.GetName(), ContainingType, type.TypeRef, Create(Context, Symbol.OriginalDefinition));
var adder = symbol.AddMethod;
var remover = symbol.RemoveMethod;
var adder = Symbol.AddMethod;
var remover = Symbol.RemoveMethod;
if (!(adder is null))
Method.Create(Context, adder);
@@ -39,10 +39,10 @@ namespace Semmle.Extraction.CSharp.Entities
BindComments();
var declSyntaxReferences = IsSourceDeclaration
? symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).ToArray()
? Symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).ToArray()
: Enumerable.Empty<SyntaxNode>();
foreach (var explicitInterface in symbol.ExplicitInterfaceImplementations.Select(impl => Type.Create(Context, impl.ContainingType)))
foreach (var explicitInterface in Symbol.ExplicitInterfaceImplementations.Select(impl => Type.Create(Context, impl.ContainingType)))
{
trapFile.explicitly_implements(this, explicitInterface.TypeRef);

View File

@@ -11,7 +11,7 @@ namespace Semmle.Extraction.CSharp.Entities
/// <summary>
/// Gets the event symbol associated with this accessor.
/// </summary>
private IEventSymbol EventSymbol => symbol.AssociatedSymbol as IEventSymbol;
private IEventSymbol EventSymbol => Symbol.AssociatedSymbol as IEventSymbol;
public override void Populate(TextWriter trapFile)
{
@@ -21,30 +21,30 @@ namespace Semmle.Extraction.CSharp.Entities
var @event = EventSymbol;
if (@event == null)
{
Context.ModelError(symbol, "Unhandled event accessor associated symbol");
Context.ModelError(Symbol, "Unhandled event accessor associated symbol");
return;
}
var parent = Event.Create(Context, @event);
int kind;
EventAccessor unboundAccessor;
if (SymbolEqualityComparer.Default.Equals(symbol, @event.AddMethod))
if (SymbolEqualityComparer.Default.Equals(Symbol, @event.AddMethod))
{
kind = 1;
unboundAccessor = Create(Context, @event.OriginalDefinition.AddMethod);
}
else if (SymbolEqualityComparer.Default.Equals(symbol, @event.RemoveMethod))
else if (SymbolEqualityComparer.Default.Equals(Symbol, @event.RemoveMethod))
{
kind = 2;
unboundAccessor = Create(Context, @event.OriginalDefinition.RemoveMethod);
}
else
{
Context.ModelError(symbol, "Undhandled event accessor kind");
Context.ModelError(Symbol, "Undhandled event accessor kind");
return;
}
trapFile.event_accessors(this, kind, symbol.Name, parent, unboundAccessor);
trapFile.event_accessors(this, kind, Symbol.Name, parent, unboundAccessor);
foreach (var l in Locations)
trapFile.event_accessor_location(this, l);

View File

@@ -29,7 +29,7 @@ namespace Semmle.Extraction.CSharp.Entities
protected sealed override void Populate(TextWriter trapFile)
{
var type = Type.HasValue ? Entities.Type.Create(cx, Type.Value) : NullType.Create(cx);
var type = Type.HasValue ? Entities.Type.Create(Context, Type.Value) : NullType.Create(Context);
trapFile.expressions(this, Kind, type.TypeRef);
if (info.Parent.IsTopLevelParent)
trapFile.expr_parent_top_level(this, info.Child, info.Parent);
@@ -39,7 +39,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (Type.HasValue && !Type.Value.HasObliviousNullability())
{
var n = NullabilityEntity.Create(cx, Nullability.Create(Type.Value));
var n = NullabilityEntity.Create(Context, Nullability.Create(Type.Value));
trapFile.type_nullability(this, n);
}
@@ -57,7 +57,7 @@ namespace Semmle.Extraction.CSharp.Entities
type.PopulateGenerics();
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => Location.symbol;
public override Microsoft.CodeAnalysis.Location ReportingLocation => Location.Symbol;
bool IExpressionParentEntity.IsTopLevelParent => false;
@@ -170,10 +170,10 @@ namespace Semmle.Extraction.CSharp.Entities
/// <param name="node">The expression.</param>
public void OperatorCall(TextWriter trapFile, ExpressionSyntax node)
{
var @operator = cx.GetSymbolInfo(node);
var @operator = Context.GetSymbolInfo(node);
if (@operator.Symbol is IMethodSymbol method)
{
var callType = GetCallType(cx, node);
var callType = GetCallType(Context, node);
if (callType == CallType.Dynamic)
{
UserOperator.OperatorSymbol(method.Name, out var operatorName);
@@ -181,7 +181,7 @@ namespace Semmle.Extraction.CSharp.Entities
return;
}
trapFile.expr_call(this, Method.Create(cx, method));
trapFile.expr_call(this, Method.Create(Context, method));
}
}
@@ -267,7 +267,7 @@ namespace Semmle.Extraction.CSharp.Entities
private void PopulateArgument(TextWriter trapFile, ArgumentSyntax arg, int child)
{
var expr = Create(cx, arg.Expression, this, child);
var expr = Create(Context, arg.Expression, this, child);
int mode;
switch (arg.RefOrOutKeyword.Kind())
{

View File

@@ -27,7 +27,7 @@ namespace Semmle.Extraction.CSharp.Entities
protected new Expression TryPopulate()
{
cx.Try(Syntax, null, () => PopulateExpression(cx.TrapWriter.Writer));
Context.Try(Syntax, null, () => PopulateExpression(Context.TrapWriter.Writer));
return this;
}
}

View File

@@ -47,12 +47,12 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
if (!(target is null))
{
cx.TrapWriter.Writer.expr_access(this, target);
Context.TrapWriter.Writer.expr_access(this, target);
}
if (implicitThis && !symbol.IsStatic)
{
This.CreateImplicit(cx, symbol.ContainingType, Location, this, -1);
This.CreateImplicit(Context, symbol.ContainingType, Location, this, -1);
}
}

View File

@@ -31,7 +31,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (TypeSyntax is null)
{
cx.ModelError(Syntax, "Array has unexpected type syntax");
Context.ModelError(Syntax, "Array has unexpected type syntax");
}
var firstLevelSizes = TypeSyntax.RankSpecifiers.First()?.Sizes ?? SyntaxFactory.SeparatedList<ExpressionSyntax>();
@@ -44,20 +44,20 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
for (var sizeIndex = 0; sizeIndex < firstLevelSizes.Count; sizeIndex++)
{
Create(cx, firstLevelSizes[sizeIndex], this, sizeIndex);
Create(Context, firstLevelSizes[sizeIndex], this, sizeIndex);
}
explicitlySized = true;
}
if (!(Initializer is null))
{
ArrayInitializer.Create(new ExpressionNodeInfo(cx, Initializer, this, InitializerIndex));
ArrayInitializer.Create(new ExpressionNodeInfo(Context, Initializer, this, InitializerIndex));
}
if (explicitlySized)
trapFile.explicitly_sized_array_creation(this);
TypeMention.Create(cx, TypeSyntax, this, Type);
TypeMention.Create(Context, TypeSyntax, this, Type);
}
private void SetArraySizes(InitializerExpressionSyntax initializer, int rank)
@@ -69,7 +69,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
return;
}
Literal.CreateGenerated(cx, this, level, cx.Compilation.GetSpecialType(SpecialType.System_Int32), initializer.Expressions.Count, Location);
Literal.CreateGenerated(Context, this, level, Context.Compilation.GetSpecialType(SpecialType.System_Int32), initializer.Expressions.Count, Location);
initializer = initializer.Expressions.FirstOrDefault() as InitializerExpressionSyntax;
}
@@ -143,7 +143,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
ArrayInitializer.Create(new ExpressionNodeInfo(cx, Syntax.Initializer, this, InitializerIndex));
ArrayInitializer.Create(new ExpressionNodeInfo(Context, Syntax.Initializer, this, InitializerIndex));
trapFile.implicitly_typed_array_creation(this);
trapFile.stackalloc_array_creation(this);
}
@@ -159,7 +159,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
if (Syntax.Initializer != null)
{
ArrayInitializer.Create(new ExpressionNodeInfo(cx, Syntax.Initializer, this, InitializerIndex));
ArrayInitializer.Create(new ExpressionNodeInfo(Context, Syntax.Initializer, this, InitializerIndex));
}
trapFile.implicitly_typed_array_creation(this);

View File

@@ -26,17 +26,17 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (operatorKind.HasValue)
{
// Convert assignment such as `a += b` into `a = a + b`.
var simpleAssignExpr = new Expression(new ExpressionInfo(cx, Type, Location, ExprKind.SIMPLE_ASSIGN, this, 2, false, null));
Create(cx, Syntax.Left, simpleAssignExpr, 1);
var opexpr = new Expression(new ExpressionInfo(cx, Type, Location, operatorKind.Value, simpleAssignExpr, 0, false, null));
Create(cx, Syntax.Left, opexpr, 0);
Create(cx, Syntax.Right, opexpr, 1);
var simpleAssignExpr = new Expression(new ExpressionInfo(Context, Type, Location, ExprKind.SIMPLE_ASSIGN, this, 2, false, null));
Create(Context, Syntax.Left, simpleAssignExpr, 1);
var opexpr = new Expression(new ExpressionInfo(Context, Type, Location, operatorKind.Value, simpleAssignExpr, 0, false, null));
Create(Context, Syntax.Left, opexpr, 0);
Create(Context, Syntax.Right, opexpr, 1);
opexpr.OperatorCall(trapFile, Syntax);
}
else
{
Create(cx, Syntax.Left, this, 1);
Create(cx, Syntax.Right, this, 0);
Create(Context, Syntax.Left, this, 1);
Create(Context, Syntax.Right, this, 0);
if (Kind == ExprKind.ADD_EVENT || Kind == ExprKind.REMOVE_EVENT)
{
@@ -148,12 +148,12 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
case ExprKind.ASSIGN_COALESCE:
return ExprKind.NULL_COALESCING;
default:
cx.ModelError(Syntax, "Couldn't unfold assignment of type " + kind);
Context.ModelError(Syntax, "Couldn't unfold assignment of type " + kind);
return ExprKind.UNKNOWN;
}
}
}
public new CallType CallType => GetCallType(cx, Syntax);
public new CallType CallType => GetCallType(Context, Syntax);
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -17,8 +17,8 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
OperatorCall(trapFile, Syntax);
CreateDeferred(cx, Syntax.Left, this, 0);
CreateDeferred(cx, Syntax.Right, this, 1);
CreateDeferred(Context, Syntax.Left, this, 0);
CreateDeferred(Context, Syntax.Right, this, 1);
}
private static ExprKind GetKind(Context cx, BinaryExpressionSyntax node)

View File

@@ -16,17 +16,17 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, ExpressionIndex);
Create(Context, Syntax.Expression, this, ExpressionIndex);
if (Kind == ExprKind.CAST)
{ // Type cast
TypeAccess.Create(new ExpressionNodeInfo(cx, Syntax.Type, this, TypeAccessIndex));
TypeAccess.Create(new ExpressionNodeInfo(Context, Syntax.Type, this, TypeAccessIndex));
}
else
{
// Type conversion
OperatorCall(trapFile, Syntax);
TypeMention.Create(cx, Syntax.Type, this, Type);
TypeMention.Create(Context, Syntax.Type, this, Type);
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -12,9 +12,9 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Condition, this, 0);
Create(cx, Syntax.WhenTrue, this, 1);
Create(cx, Syntax.WhenFalse, this, 2);
Create(Context, Syntax.Condition, this, 0);
Create(Context, Syntax.WhenTrue, this, 1);
Create(Context, Syntax.WhenFalse, this, 2);
}
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
TypeAccess.Create(cx, Syntax.Type, this, 0);
TypeAccess.Create(Context, Syntax.Type, this, 0);
}
}
}

View File

@@ -22,22 +22,22 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
if (Kind == ExprKind.POINTER_INDIRECTION)
{
var qualifierInfo = new ExpressionNodeInfo(cx, qualifier, this, 0);
var add = new Expression(new ExpressionInfo(cx, qualifierInfo.Type, Location, ExprKind.ADD, this, 0, false, null));
var qualifierInfo = new ExpressionNodeInfo(Context, qualifier, this, 0);
var add = new Expression(new ExpressionInfo(Context, qualifierInfo.Type, Location, ExprKind.ADD, this, 0, false, null));
qualifierInfo.SetParent(add, 0);
CreateFromNode(qualifierInfo);
PopulateArguments(trapFile, argumentList, 1);
}
else
{
Create(cx, qualifier, this, -1);
Create(Context, qualifier, this, -1);
PopulateArguments(trapFile, argumentList, 0);
var symbolInfo = cx.GetSymbolInfo(base.Syntax);
var symbolInfo = Context.GetSymbolInfo(base.Syntax);
if (symbolInfo.Symbol is IPropertySymbol indexer)
{
trapFile.expr_access(this, Indexer.Create(cx, indexer));
trapFile.expr_access(this, Indexer.Create(Context, indexer));
}
}
}

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
public ImplicitCast(ExpressionNodeInfo info)
: base(new ExpressionInfo(info.Context, info.ConvertedType, info.Location, ExprKind.CAST, info.Parent, info.Child, true, info.ExprValue))
{
Expr = Factory.Create(new ExpressionNodeInfo(cx, info.Node, this, 0));
Expr = Factory.Create(new ExpressionNodeInfo(Context, info.Node, this, 0));
}
public ImplicitCast(ExpressionNodeInfo info, IMethodSymbol method)
@@ -22,11 +22,11 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
Expr = Factory.Create(info.SetParent(this, 0));
var target = Method.Create(cx, method);
var target = Method.Create(Context, method);
if (target != null)
cx.TrapWriter.Writer.expr_call(this, target);
Context.TrapWriter.Writer.expr_call(this, target);
else
cx.ModelError(info.Node, "Failed to resolve target for operator invocation");
Context.ModelError(info.Node, "Failed to resolve target for operator invocation");
}
/// <summary>

View File

@@ -26,12 +26,12 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (e.Kind() == SyntaxKind.ArrayInitializerExpression)
{
// Recursively create another array initializer
Create(new ExpressionNodeInfo(cx, (InitializerExpressionSyntax)e, this, child++));
Create(new ExpressionNodeInfo(Context, (InitializerExpressionSyntax)e, this, child++));
}
else
{
// Create the expression normally.
Create(cx, e, this, child++);
Create(Context, e, this, child++);
}
}
}
@@ -61,7 +61,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
ArrayInitializer.Create(new ExpressionNodeInfo(cx, Syntax, this, -1));
ArrayInitializer.Create(new ExpressionNodeInfo(Context, Syntax, this, -1));
trapFile.implicitly_typed_array_creation(this);
}
}
@@ -81,9 +81,9 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
if (init is AssignmentExpressionSyntax assignment)
{
var assignmentInfo = new ExpressionNodeInfo(cx, init, this, child++).SetKind(ExprKind.SIMPLE_ASSIGN);
var assignmentInfo = new ExpressionNodeInfo(Context, init, this, child++).SetKind(ExprKind.SIMPLE_ASSIGN);
var assignmentEntity = new Expression(assignmentInfo);
var typeInfoRight = cx.GetTypeInfo(assignment.Right);
var typeInfoRight = Context.GetTypeInfo(assignment.Right);
if (typeInfoRight.Type is null)
// The type may be null for nested initializers such as
// ```csharp
@@ -92,15 +92,15 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
// In this case we take the type from the assignment
// `As = { [0] = a }` instead
typeInfoRight = assignmentInfo.TypeInfo;
CreateFromNode(new ExpressionNodeInfo(cx, assignment.Right, assignmentEntity, 0, typeInfoRight));
CreateFromNode(new ExpressionNodeInfo(Context, assignment.Right, assignmentEntity, 0, typeInfoRight));
var target = cx.GetSymbolInfo(assignment.Left);
var target = Context.GetSymbolInfo(assignment.Left);
// If the target is null, then assume that this is an array initializer (of the form `[...] = ...`)
var access = target.Symbol is null ?
new Expression(new ExpressionNodeInfo(cx, assignment.Left, assignmentEntity, 1).SetKind(ExprKind.ARRAY_ACCESS)) :
Access.Create(new ExpressionNodeInfo(cx, assignment.Left, assignmentEntity, 1), target.Symbol, false, cx.CreateEntity(target.Symbol));
new Expression(new ExpressionNodeInfo(Context, assignment.Left, assignmentEntity, 1).SetKind(ExprKind.ARRAY_ACCESS)) :
Access.Create(new ExpressionNodeInfo(Context, assignment.Left, assignmentEntity, 1), target.Symbol, false, Context.CreateEntity(target.Symbol));
if (assignment.Left is ImplicitElementAccessSyntax iea)
{
@@ -109,14 +109,14 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var indexChild = 0;
foreach (var arg in iea.ArgumentList.Arguments)
{
Expression.Create(cx, arg.Expression, access, indexChild++);
Expression.Create(Context, arg.Expression, access, indexChild++);
}
}
}
else
{
cx.ModelError(init, "Unexpected object initialization");
Create(cx, init, this, child++);
Context.ModelError(init, "Unexpected object initialization");
Create(Context, init, this, child++);
}
}
}
@@ -133,16 +133,16 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var child = 0;
foreach (var i in Syntax.Expressions)
{
var collectionInfo = cx.GetModel(Syntax).GetCollectionInitializerSymbolInfo(i);
var addMethod = Method.Create(cx, collectionInfo.Symbol as IMethodSymbol);
var voidType = AnnotatedTypeSymbol.CreateNotAnnotated(cx.Compilation.GetSpecialType(SpecialType.System_Void));
var collectionInfo = Context.GetModel(Syntax).GetCollectionInitializerSymbolInfo(i);
var addMethod = Method.Create(Context, collectionInfo.Symbol as IMethodSymbol);
var voidType = AnnotatedTypeSymbol.CreateNotAnnotated(Context.Compilation.GetSpecialType(SpecialType.System_Void));
var invocation = new Expression(new ExpressionInfo(cx, voidType, cx.CreateLocation(i.GetLocation()), ExprKind.METHOD_INVOCATION, this, child++, false, null));
var invocation = new Expression(new ExpressionInfo(Context, voidType, Context.CreateLocation(i.GetLocation()), ExprKind.METHOD_INVOCATION, this, child++, false, null));
if (addMethod != null)
trapFile.expr_call(invocation, addMethod);
else
cx.ModelError(Syntax, "Unable to find an Add() method for collection initializer");
Context.ModelError(Syntax, "Unable to find an Add() method for collection initializer");
if (i.Kind() == SyntaxKind.ComplexElementInitializerExpression)
{
@@ -154,12 +154,12 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var addChild = 0;
foreach (var arg in init.Expressions)
{
Create(cx, arg, invocation, addChild++);
Create(Context, arg, invocation, addChild++);
}
}
else
{
Create(cx, i, invocation, 0);
Create(Context, i, invocation, 0);
}
}
}

View File

@@ -22,12 +22,12 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
case SyntaxKind.Interpolation:
var interpolation = (InterpolationSyntax)c;
Create(cx, interpolation.Expression, this, child++);
Create(Context, interpolation.Expression, this, child++);
break;
case SyntaxKind.InterpolatedStringText:
// Create a string literal
var interpolatedText = (InterpolatedStringTextSyntax)c;
new Expression(new ExpressionInfo(cx, Type, cx.CreateLocation(c.GetLocation()), ExprKind.STRING_LITERAL, this, child++, false, interpolatedText.TextToken.Text));
new Expression(new ExpressionInfo(Context, Type, Context.CreateLocation(c.GetLocation()), ExprKind.STRING_LITERAL, this, child++, false, interpolatedText.TextToken.Text));
break;
default:
throw new InternalError(c, $"Unhandled interpolation kind {c.Kind()}");

View File

@@ -37,15 +37,15 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
memberName = memberAccess.Name.Identifier.Text;
if (Syntax.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
// Qualified method call; `x.M()`
Create(cx, memberAccess.Expression, this, child++);
Create(Context, memberAccess.Expression, this, child++);
else
// Pointer member access; `x->M()`
Create(cx, Syntax.Expression, this, child++);
Create(Context, Syntax.Expression, this, child++);
break;
case MemberBindingExpressionSyntax memberBinding:
// Conditionally qualified method call; `x?.M()`
memberName = memberBinding.Name.Identifier.Text;
Create(cx, FindConditionalQualifier(memberBinding), this, child++);
Create(Context, FindConditionalQualifier(memberBinding), this, child++);
MakeConditional(trapFile);
break;
case SimpleNameSyntax simpleName when (Kind == ExprKind.METHOD_INVOCATION):
@@ -55,10 +55,10 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
// Implicit `this` qualifier; add explicitly
if (cx.GetModel(Syntax).GetEnclosingSymbol(Location.symbol.SourceSpan.Start) is IMethodSymbol callingMethod)
This.CreateImplicit(cx, callingMethod.ContainingType, Location, this, child++);
if (Context.GetModel(Syntax).GetEnclosingSymbol(Location.Symbol.SourceSpan.Start) is IMethodSymbol callingMethod)
This.CreateImplicit(Context, callingMethod.ContainingType, Location, this, child++);
else
cx.ModelError(Syntax, "Couldn't determine implicit this type");
Context.ModelError(Syntax, "Couldn't determine implicit this type");
}
else
{
@@ -68,7 +68,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
break;
default:
// Delegate or function pointer call; `d()`
Create(cx, Syntax.Expression, this, child++);
Create(Context, Syntax.Expression, this, child++);
break;
}
@@ -78,7 +78,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (memberName != null)
trapFile.dynamic_member_name(this, memberName);
else
cx.ModelError(Syntax, "Unable to get name for dynamic call.");
Context.ModelError(Syntax, "Unable to get name for dynamic call.");
}
PopulateArguments(trapFile, Syntax.ArgumentList, child);
@@ -86,11 +86,11 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (target == null)
{
if (!isDynamicCall && !IsDelegateLikeCall(info))
cx.ModelError(Syntax, "Unable to resolve target for call. (Compilation error?)");
Context.ModelError(Syntax, "Unable to resolve target for call. (Compilation error?)");
return;
}
var targetKey = Method.Create(cx, target);
var targetKey = Method.Create(Context, target);
trapFile.expr_call(this, targetKey);
}
@@ -125,7 +125,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
.Where(method => method.Parameters.Length >= Syntax.ArgumentList.Arguments.Count)
.Where(method => method.Parameters.Count(p => !p.HasExplicitDefaultValue) <= Syntax.ArgumentList.Arguments.Count);
return cx.Extractor.Standalone ?
return Context.Extractor.Standalone ?
candidates.FirstOrDefault() :
candidates.SingleOrDefault();
}

View File

@@ -12,8 +12,8 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Expressions.Pattern.Create(cx, Syntax.Pattern, this, 1);
Create(Context, Syntax.Expression, this, 0);
Expressions.Pattern.Create(Context, Syntax.Pattern, this, 1);
}
public static Expression Create(ExpressionNodeInfo info) => new IsPattern(info).TryPopulate();

View File

@@ -17,34 +17,34 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
private void VisitParameter(ParameterSyntax p)
{
var symbol = cx.GetModel(p).GetDeclaredSymbol(p);
Parameter.Create(cx, symbol, this);
var symbol = Context.GetModel(p).GetDeclaredSymbol(p);
Parameter.Create(Context, symbol, this);
}
private Lambda(ExpressionNodeInfo info, CSharpSyntaxNode body, IEnumerable<ParameterSyntax> @params)
: base(info)
{
if (cx.GetModel(info.Node).GetSymbolInfo(info.Node).Symbol is IMethodSymbol symbol)
if (Context.GetModel(info.Node).GetSymbolInfo(info.Node).Symbol is IMethodSymbol symbol)
{
Modifier.ExtractModifiers(cx, info.Context.TrapWriter.Writer, this, symbol);
Modifier.ExtractModifiers(Context, info.Context.TrapWriter.Writer, this, symbol);
}
else
{
cx.ModelError(info.Node, "Unknown declared symbol");
Context.ModelError(info.Node, "Unknown declared symbol");
}
// No need to use `Populate` as the population happens later
cx.PopulateLater(() =>
Context.PopulateLater(() =>
{
foreach (var param in @params)
VisitParameter(param);
if (body is ExpressionSyntax exprBody)
Create(cx, exprBody, this, 0);
Create(Context, exprBody, this, 0);
else if (body is BlockSyntax blockBody)
Statements.Block.Create(cx, blockBody, this, 0);
Statements.Block.Create(Context, blockBody, this, 0);
else
cx.ModelError(body, "Unhandled lambda body");
Context.ModelError(body, "Unhandled lambda body");
});
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -9,16 +9,16 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
private MemberAccess(ExpressionNodeInfo info, ExpressionSyntax qualifier, ISymbol target) : base(info)
{
var trapFile = info.Context.TrapWriter.Writer;
Qualifier = Create(cx, qualifier, this, -1);
Qualifier = Create(Context, qualifier, this, -1);
if (target == null)
{
if (info.Kind != ExprKind.DYNAMIC_MEMBER_ACCESS)
cx.ModelError(info.Node, "Could not determine target for member access");
Context.ModelError(info.Node, "Could not determine target for member access");
}
else
{
var t = cx.CreateEntity(target);
var t = Context.CreateEntity(target);
trapFile.expr_access(this, t);
}
}

View File

@@ -17,32 +17,32 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
var target = cx.GetSymbolInfo(Syntax);
var target = Context.GetSymbolInfo(Syntax);
var method = (IMethodSymbol)target.Symbol;
if (method != null)
{
trapFile.expr_call(this, Method.Create(cx, method));
trapFile.expr_call(this, Method.Create(Context, method));
}
var child = 0;
var objectInitializer = Syntax.Initializers.Any() ?
new Expression(new ExpressionInfo(cx, Type, Location, ExprKind.OBJECT_INIT, this, -1, false, null)) :
new Expression(new ExpressionInfo(Context, Type, Location, ExprKind.OBJECT_INIT, this, -1, false, null)) :
null;
foreach (var init in Syntax.Initializers)
{
// Create an "assignment"
var property = cx.GetModel(init).GetDeclaredSymbol(init);
var propEntity = Property.Create(cx, property);
var property = Context.GetModel(init).GetDeclaredSymbol(init);
var propEntity = Property.Create(Context, property);
var type = property.GetAnnotatedType();
var loc = cx.CreateLocation(init.GetLocation());
var loc = Context.CreateLocation(init.GetLocation());
var assignment = new Expression(new ExpressionInfo(cx, type, loc, ExprKind.SIMPLE_ASSIGN, objectInitializer, child++, false, null));
Create(cx, init.Expression, assignment, 0);
Property.Create(cx, property);
var assignment = new Expression(new ExpressionInfo(Context, type, loc, ExprKind.SIMPLE_ASSIGN, objectInitializer, child++, false, null));
Create(Context, init.Expression, assignment, 0);
Property.Create(Context, property);
var access = new Expression(new ExpressionInfo(cx, type, loc, ExprKind.PROPERTY_ACCESS, assignment, 1, false, null));
var access = new Expression(new ExpressionInfo(Context, type, loc, ExprKind.PROPERTY_ACCESS, assignment, 1, false, null));
trapFile.expr_access(access, propEntity);
}
}

View File

@@ -22,22 +22,22 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
PopulateArguments(trapFile, Syntax.ArgumentList, 0);
}
var target = cx.GetModel(Syntax).GetSymbolInfo(Syntax);
var target = Context.GetModel(Syntax).GetSymbolInfo(Syntax);
if (target.Symbol is IMethodSymbol method)
{
trapFile.expr_call(this, Method.Create(cx, method));
trapFile.expr_call(this, Method.Create(Context, method));
}
if (IsDynamicObjectCreation(cx, Syntax))
if (IsDynamicObjectCreation(Context, Syntax))
{
if (cx.GetModel(Syntax).GetTypeInfo(Syntax).Type is INamedTypeSymbol type &&
if (Context.GetModel(Syntax).GetTypeInfo(Syntax).Type is INamedTypeSymbol type &&
!string.IsNullOrEmpty(type.Name))
{
trapFile.dynamic_member_name(this, type.Name);
}
else
{
cx.ModelError(Syntax, "Unable to get name for dynamic object creation.");
Context.ModelError(Syntax, "Unable to get name for dynamic object creation.");
}
}
@@ -46,13 +46,13 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
switch (Syntax.Initializer.Kind())
{
case SyntaxKind.CollectionInitializerExpression:
CollectionInitializer.Create(new ExpressionNodeInfo(cx, Syntax.Initializer, this, -1).SetType(Type));
CollectionInitializer.Create(new ExpressionNodeInfo(Context, Syntax.Initializer, this, -1).SetType(Type));
break;
case SyntaxKind.ObjectInitializerExpression:
ObjectInitializer.Create(new ExpressionNodeInfo(cx, Syntax.Initializer, this, -1).SetType(Type));
ObjectInitializer.Create(new ExpressionNodeInfo(Context, Syntax.Initializer, this, -1).SetType(Type));
break;
default:
cx.ModelError("Unhandled initializer in object creation");
Context.ModelError("Unhandled initializer in object creation");
break;
}
}

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
base.PopulateExpression(trapFile);
TypeMention.Create(cx, Syntax.Type, this, Type);
TypeMention.Create(Context, Syntax.Type, this, Type);
}
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
// !! We do not currently look at the member (or store the member name).
}

View File

@@ -20,7 +20,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, operand, this, 0);
Create(Context, operand, this, 0);
OperatorCall(trapFile, Syntax);
if ((operatorKind == ExprKind.POST_INCR || operatorKind == ExprKind.POST_DECR) &&

View File

@@ -13,9 +13,9 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
if (!(Syntax.LeftOperand is null))
Expression.Create(cx, Syntax.LeftOperand, this, 0);
Expression.Create(Context, Syntax.LeftOperand, this, 0);
if (!(Syntax.RightOperand is null))
Expression.Create(cx, Syntax.RightOperand, this, 1);
Expression.Create(Context, Syntax.RightOperand, this, 1);
}
public static Expression Create(ExpressionNodeInfo info) => new RangeExpression(info).TryPopulate();

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -12,8 +12,8 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(cx, Syntax.Type, this, 1); // A type-access
Create(Context, Syntax.Expression, this, 0);
Create(Context, Syntax.Type, this, 1); // A type-access
}
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
TypeAccess.Create(cx, Syntax.Type, this, 0);
TypeAccess.Create(Context, Syntax.Type, this, 0);
}
}
}

View File

@@ -17,10 +17,10 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
SwitchedExpr = Expression.Create(cx, Syntax.GoverningExpression, this, -1);
SwitchedExpr = Expression.Create(Context, Syntax.GoverningExpression, this, -1);
for (var i = 0; i < Syntax.Arms.Count; i++)
{
new SwitchCase(cx, Syntax.Arms[i], this, i);
new SwitchCase(Context, Syntax.Arms[i], this, i);
}
}
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -18,7 +18,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var child = 0;
foreach (var argument in Syntax.Arguments.Select(a => a.Expression))
{
Expression.Create(cx, argument, this, child++);
Expression.Create(Context, argument, this, child++);
}
}
}

View File

@@ -18,17 +18,17 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (Type?.Symbol.ContainingType is null)
{
// namespace qualifier
TypeMention.Create(cx, maes.Name, this, Type, Syntax.GetLocation());
TypeMention.Create(Context, maes.Name, this, Type, Syntax.GetLocation());
}
else
{
// type qualifier
TypeMention.Create(cx, maes.Name, this, Type);
Create(cx, maes.Expression, this, -1);
TypeMention.Create(Context, maes.Name, this, Type);
Create(Context, maes.Expression, this, -1);
}
return;
default:
TypeMention.Create(cx, (TypeSyntax)Syntax, this, Type);
TypeMention.Create(Context, (TypeSyntax)Syntax, this, Type);
return;
}
}

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
TypeAccess.Create(cx, Syntax.Type, this, TypeAccessIndex);
TypeAccess.Create(Context, Syntax.Type, this, TypeAccessIndex);
}
public static Expression CreateGenerated(Context cx, IExpressionParentEntity parent, int childIndex, Microsoft.CodeAnalysis.ITypeSymbol type, Extraction.Entities.Location location)

View File

@@ -23,7 +23,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Operand, this, 0);
Create(Context, Syntax.Operand, this, 0);
OperatorCall(trapFile, Syntax);
if ((operatorKind == ExprKind.PRE_INCR || operatorKind == ExprKind.PRE_DECR) &&

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
Create(cx, Syntax.Expression, this, 0);
Create(Context, Syntax.Expression, this, 0);
}
}
}

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities
private Field(Context cx, IFieldSymbol init)
: base(cx, init)
{
type = new Lazy<Type>(() => Entities.Type.Create(cx, symbol.Type));
type = new Lazy<Type>(() => Entities.Type.Create(cx, Symbol.Type));
}
public static Field Create(Context cx, IFieldSymbol field) => FieldFactory.Instance.CreateEntityFromSymbol(cx, field);
@@ -22,43 +22,43 @@ namespace Semmle.Extraction.CSharp.Entities
// Do not populate backing fields.
// Populate Tuple fields.
public override bool NeedsPopulation =>
(base.NeedsPopulation && !symbol.IsImplicitlyDeclared) || symbol.ContainingType.IsTupleType;
(base.NeedsPopulation && !Symbol.IsImplicitlyDeclared) || Symbol.ContainingType.IsTupleType;
public override void Populate(TextWriter trapFile)
{
PopulateMetadataHandle(trapFile);
PopulateAttributes();
ContainingType.PopulateGenerics();
PopulateNullability(trapFile, symbol.GetAnnotatedType());
PopulateNullability(trapFile, Symbol.GetAnnotatedType());
var unboundFieldKey = Field.Create(Context, symbol.OriginalDefinition);
trapFile.fields(this, (symbol.IsConst ? 2 : 1), symbol.Name, ContainingType, Type.TypeRef, unboundFieldKey);
var unboundFieldKey = Field.Create(Context, Symbol.OriginalDefinition);
trapFile.fields(this, (Symbol.IsConst ? 2 : 1), Symbol.Name, ContainingType, Type.TypeRef, unboundFieldKey);
PopulateModifiers(trapFile);
if (symbol.IsVolatile)
if (Symbol.IsVolatile)
Modifier.HasModifier(Context, trapFile, this, "volatile");
if (symbol.IsConst)
if (Symbol.IsConst)
{
Modifier.HasModifier(Context, trapFile, this, "const");
if (symbol.HasConstantValue)
if (Symbol.HasConstantValue)
{
trapFile.constant_value(this, Expression.ValueAsString(symbol.ConstantValue));
trapFile.constant_value(this, Expression.ValueAsString(Symbol.ConstantValue));
}
}
foreach (var l in Locations)
trapFile.field_location(this, l);
if (!IsSourceDeclaration || !symbol.FromSource())
if (!IsSourceDeclaration || !Symbol.FromSource())
return;
Context.BindComments(this, Location.symbol);
Context.BindComments(this, Location.Symbol);
var child = 0;
foreach (var initializer in symbol.DeclaringSyntaxReferences
foreach (var initializer in Symbol.DeclaringSyntaxReferences
.Select(n => n.GetSyntax())
.OfType<VariableDeclaratorSyntax>()
.Where(n => n.Initializer != null))
@@ -69,21 +69,21 @@ namespace Semmle.Extraction.CSharp.Entities
var fieldAccess = AddInitializerAssignment(trapFile, initializer.Initializer.Value, loc, null, ref child);
if (!symbol.IsStatic)
if (!Symbol.IsStatic)
{
This.CreateImplicit(Context, symbol.ContainingType, Location, fieldAccess, -1);
This.CreateImplicit(Context, Symbol.ContainingType, Location, fieldAccess, -1);
}
});
}
foreach (var initializer in symbol.DeclaringSyntaxReferences
foreach (var initializer in Symbol.DeclaringSyntaxReferences
.Select(n => n.GetSyntax())
.OfType<EnumMemberDeclarationSyntax>()
.Where(n => n.EqualsValue != null))
{
// Mark fields that have explicit initializers.
var constValue = symbol.HasConstantValue
? Expression.ValueAsString(symbol.ConstantValue)
var constValue = Symbol.HasConstantValue
? Expression.ValueAsString(Symbol.ConstantValue)
: null;
var loc = Context.CreateLocation(initializer.GetLocation());
@@ -93,7 +93,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (IsSourceDeclaration)
{
foreach (var syntax in symbol.DeclaringSyntaxReferences
foreach (var syntax in Symbol.DeclaringSyntaxReferences
.Select(d => d.GetSyntax())
.OfType<VariableDeclaratorSyntax>()
.Select(d => d.Parent)
@@ -107,7 +107,7 @@ namespace Semmle.Extraction.CSharp.Entities
private Expression AddInitializerAssignment(TextWriter trapFile, ExpressionSyntax initializer, Extraction.Entities.Location loc,
string constValue, ref int child)
{
var type = symbol.GetAnnotatedType();
var type = Symbol.GetAnnotatedType();
var simpleAssignExpr = new Expression(new ExpressionInfo(Context, type, loc, ExprKind.SIMPLE_ASSIGN, this, child++, false, constValue));
Expression.CreateFromNode(new ExpressionNodeInfo(Context, initializer, simpleAssignExpr, 0));
var access = new Expression(new ExpressionInfo(Context, type, Location, ExprKind.FIELD_ACCESS, simpleAssignExpr, 1, false, constValue));
@@ -124,7 +124,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.Write(" ");
trapFile.WriteSubId(ContainingType);
trapFile.Write('.');
trapFile.Write(symbol.Name);
trapFile.Write(Symbol.Name);
trapFile.Write(";field");
}

View File

@@ -10,22 +10,22 @@ namespace Semmle.Extraction.CSharp.Entities
protected Indexer(Context cx, IPropertySymbol init)
: base(cx, init) { }
private Indexer OriginalDefinition => IsSourceDeclaration ? this : Create(Context, symbol.OriginalDefinition);
private Indexer OriginalDefinition => IsSourceDeclaration ? this : Create(Context, Symbol.OriginalDefinition);
public override void Populate(TextWriter trapFile)
{
PopulateNullability(trapFile, symbol.GetAnnotatedType());
PopulateNullability(trapFile, Symbol.GetAnnotatedType());
var type = Type.Create(Context, symbol.Type);
trapFile.indexers(this, symbol.GetName(useMetadataName: true), ContainingType, type.TypeRef, OriginalDefinition);
var type = Type.Create(Context, Symbol.Type);
trapFile.indexers(this, Symbol.GetName(useMetadataName: true), ContainingType, type.TypeRef, OriginalDefinition);
foreach (var l in Locations)
trapFile.indexer_location(this, l);
var getter = symbol.GetMethod;
var setter = symbol.SetMethod;
var getter = Symbol.GetMethod;
var setter = Symbol.SetMethod;
if (getter is null && setter is null)
Context.ModelError(symbol, "No indexer accessor defined");
Context.ModelError(Symbol, "No indexer accessor defined");
if (!(getter is null))
Method.Create(Context, getter);
@@ -33,10 +33,10 @@ namespace Semmle.Extraction.CSharp.Entities
if (!(setter is null))
Method.Create(Context, setter);
for (var i = 0; i < symbol.Parameters.Length; ++i)
for (var i = 0; i < Symbol.Parameters.Length; ++i)
{
var original = Parameter.Create(Context, symbol.OriginalDefinition.Parameters[i], OriginalDefinition);
Parameter.Create(Context, symbol.Parameters[i], this, original);
var original = Parameter.Create(Context, Symbol.OriginalDefinition.Parameters[i], OriginalDefinition);
Parameter.Create(Context, Symbol.Parameters[i], this, original);
}
if (IsSourceDeclaration)
@@ -46,7 +46,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
// The expression may need to reference parameters in the getter.
// So we need to arrange that the expression is populated after the getter.
Context.PopulateLater(() => Expression.CreateFromNode(new ExpressionNodeInfo(Context, expressionBody, this, 0).SetType(symbol.GetAnnotatedType())));
Context.PopulateLater(() => Expression.CreateFromNode(new ExpressionNodeInfo(Context, expressionBody, this, 0).SetType(Symbol.GetAnnotatedType())));
}
}
@@ -54,11 +54,11 @@ namespace Semmle.Extraction.CSharp.Entities
BindComments();
var declSyntaxReferences = IsSourceDeclaration
? symbol.DeclaringSyntaxReferences.
? Symbol.DeclaringSyntaxReferences.
Select(d => d.GetSyntax()).OfType<IndexerDeclarationSyntax>().ToArray()
: Enumerable.Empty<IndexerDeclarationSyntax>();
foreach (var explicitInterface in symbol.ExplicitInterfaceImplementations.Select(impl => Type.Create(Context, impl.ContainingType)))
foreach (var explicitInterface in Symbol.ExplicitInterfaceImplementations.Select(impl => Type.Create(Context, impl.ContainingType)))
{
trapFile.explicitly_implements(this, explicitInterface.TypeRef);
@@ -77,9 +77,9 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.WriteSubId(ContainingType);
trapFile.Write('.');
trapFile.Write(symbol.MetadataName);
trapFile.Write(Symbol.MetadataName);
trapFile.Write('(');
trapFile.BuildList(",", symbol.Parameters, (p, tb0) => tb0.WriteSubId(Type.Create(Context, p.Type)));
trapFile.BuildList(",", Symbol.Parameters, (p, tb0) => tb0.WriteSubId(Type.Create(Context, p.Type)));
trapFile.Write(");indexer");
}
@@ -87,11 +87,11 @@ namespace Semmle.Extraction.CSharp.Entities
{
get
{
return symbol.DeclaringSyntaxReferences
return Symbol.DeclaringSyntaxReferences
.Select(r => r.GetSyntax())
.OfType<IndexerDeclarationSyntax>()
.Select(s => s.GetLocation())
.Concat(symbol.Locations)
.Concat(Symbol.Locations)
.First();
}
}

View File

@@ -34,10 +34,10 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateMethod(trapFile);
PopulateModifiers(trapFile);
var originalDefinition = IsSourceDeclaration ? this : Create(Context, symbol.OriginalDefinition);
var returnType = Type.Create(Context, symbol.ReturnType);
trapFile.local_functions(this, symbol.Name, returnType, originalDefinition);
ExtractRefReturn(trapFile, symbol, this);
var originalDefinition = IsSourceDeclaration ? this : Create(Context, Symbol.OriginalDefinition);
var returnType = Type.Create(Context, Symbol.ReturnType);
trapFile.local_functions(this, Symbol.Name, returnType, originalDefinition);
ExtractRefReturn(trapFile, Symbol, this);
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NeedsLabel;

View File

@@ -23,12 +23,12 @@ namespace Semmle.Extraction.CSharp.Entities
public void PopulateManual(Expression parent, bool isVar)
{
var trapFile = Context.TrapWriter.Writer;
var (kind, type) = symbol is ILocalSymbol l
var (kind, type) = Symbol is ILocalSymbol l
? (l.IsRef ? 3 : l.IsConst ? 2 : 1, l.GetAnnotatedType())
: (1, parent.Type);
trapFile.localvars(this, kind, symbol.Name, isVar ? 1 : 0, Type.Create(Context, type).TypeRef, parent);
trapFile.localvars(this, kind, Symbol.Name, isVar ? 1 : 0, Type.Create(Context, type).TypeRef, parent);
if (symbol is ILocalSymbol local)
if (Symbol is ILocalSymbol local)
{
PopulateNullability(trapFile, local.GetAnnotatedType());
if (local.IsRef)
@@ -47,7 +47,7 @@ namespace Semmle.Extraction.CSharp.Entities
private void DefineConstantValue(TextWriter trapFile)
{
if (symbol is ILocalSymbol local && local.HasConstantValue)
if (Symbol is ILocalSymbol local && local.HasConstantValue)
{
trapFile.constant_value(this, Expression.ValueAsString(local.ConstantValue));
}

View File

@@ -16,8 +16,8 @@ namespace Semmle.Extraction.CSharp.Entities
protected void PopulateParameters()
{
var originalMethod = OriginalDefinition;
IEnumerable<IParameterSymbol> parameters = symbol.Parameters;
IEnumerable<IParameterSymbol> originalParameters = originalMethod.symbol.Parameters;
IEnumerable<IParameterSymbol> parameters = Symbol.Parameters;
IEnumerable<IParameterSymbol> originalParameters = originalMethod.Symbol.Parameters;
if (IsReducedExtension)
{
@@ -25,14 +25,14 @@ namespace Semmle.Extraction.CSharp.Entities
{
// Non-generic reduced extensions must be extracted exactly like the
// non-reduced counterparts
parameters = symbol.ReducedFrom.Parameters;
parameters = Symbol.ReducedFrom.Parameters;
}
else
{
// Constructed reduced extensions are special because their non-reduced
// counterparts are not constructed. Therefore, we need to manually add
// the `this` parameter based on the type of the receiver
var originalThisParamSymbol = originalMethod.symbol.Parameters.First();
var originalThisParamSymbol = originalMethod.Symbol.Parameters.First();
var originalThisParam = Parameter.Create(Context, originalThisParamSymbol, originalMethod);
ConstructedExtensionParameter.Create(Context, this, originalThisParam);
originalParameters = originalParameters.Skip(1);
@@ -47,7 +47,7 @@ namespace Semmle.Extraction.CSharp.Entities
Parameter.Create(Context, p.paramSymbol, this, original);
}
if (symbol.IsVararg)
if (Symbol.IsVararg)
{
// Mono decided that "__arglist" should be an explicit parameter,
// so now we need to populate it.
@@ -101,7 +101,7 @@ namespace Semmle.Extraction.CSharp.Entities
public void Overrides(TextWriter trapFile)
{
foreach (var explicitInterface in symbol.ExplicitInterfaceImplementations
foreach (var explicitInterface in Symbol.ExplicitInterfaceImplementations
.Where(sym => sym.MethodKind == MethodKind.Ordinary)
.Select(impl => Type.Create(Context, impl.ContainingType)))
{
@@ -109,14 +109,14 @@ namespace Semmle.Extraction.CSharp.Entities
if (IsSourceDeclaration)
{
foreach (var syntax in symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).OfType<MethodDeclarationSyntax>())
foreach (var syntax in Symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).OfType<MethodDeclarationSyntax>())
TypeMention.Create(Context, syntax.ExplicitInterfaceSpecifier.Name, this, explicitInterface);
}
}
if (symbol.OverriddenMethod != null)
if (Symbol.OverriddenMethod != null)
{
trapFile.overrides(this, Method.Create(Context, symbol.OverriddenMethod));
trapFile.overrides(this, Method.Create(Context, Symbol.OverriddenMethod));
}
}
@@ -125,22 +125,22 @@ namespace Semmle.Extraction.CSharp.Entities
/// </summary>
private static void BuildMethodId(Method m, TextWriter trapFile)
{
m.symbol.ReturnType.BuildOrWriteId(m.Context, trapFile, m.symbol);
m.Symbol.ReturnType.BuildOrWriteId(m.Context, trapFile, m.Symbol);
trapFile.Write(" ");
trapFile.WriteSubId(m.ContainingType);
AddExplicitInterfaceQualifierToId(m.Context, trapFile, m.symbol.ExplicitInterfaceImplementations);
AddExplicitInterfaceQualifierToId(m.Context, trapFile, m.Symbol.ExplicitInterfaceImplementations);
trapFile.Write(".");
trapFile.Write(m.symbol.Name);
trapFile.Write(m.Symbol.Name);
if (m.symbol.IsGenericMethod)
if (m.Symbol.IsGenericMethod)
{
if (SymbolEqualityComparer.Default.Equals(m.symbol, m.symbol.OriginalDefinition))
if (SymbolEqualityComparer.Default.Equals(m.Symbol, m.Symbol.OriginalDefinition))
{
trapFile.Write('`');
trapFile.Write(m.symbol.TypeParameters.Length);
trapFile.Write(m.Symbol.TypeParameters.Length);
}
else
{
@@ -149,13 +149,13 @@ namespace Semmle.Extraction.CSharp.Entities
// Type arguments with different nullability can result in
// a constructed method with different nullability of its parameters and return type,
// so we need to create a distinct database entity for it.
trapFile.BuildList(",", m.symbol.GetAnnotatedTypeArguments(), (ta, tb0) => { ta.Symbol.BuildOrWriteId(m.Context, tb0, m.symbol); trapFile.Write((int)ta.Nullability); });
trapFile.BuildList(",", m.Symbol.GetAnnotatedTypeArguments(), (ta, tb0) => { ta.Symbol.BuildOrWriteId(m.Context, tb0, m.Symbol); trapFile.Write((int)ta.Nullability); });
trapFile.Write('>');
}
}
AddParametersToId(m.Context, trapFile, m.symbol);
switch (m.symbol.MethodKind)
AddParametersToId(m.Context, trapFile, m.Symbol);
switch (m.Symbol.MethodKind)
{
case MethodKind.PropertyGet:
trapFile.Write(";getter");
@@ -224,7 +224,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.AppendList(",", explicitInterfaceImplementations.Select(impl => cx.CreateEntity(impl.ContainingType)));
}
public virtual string Name => symbol.Name;
public virtual string Name => Symbol.Name;
/// <summary>
/// Creates a method of the appropriate subtype.
@@ -278,28 +278,28 @@ namespace Semmle.Extraction.CSharp.Entities
public Method OriginalDefinition =>
IsReducedExtension
? Create(Context, symbol.ReducedFrom)
: Create(Context, symbol.OriginalDefinition);
? Create(Context, Symbol.ReducedFrom)
: Create(Context, Symbol.OriginalDefinition);
public override Microsoft.CodeAnalysis.Location FullLocation => ReportingLocation;
public override bool IsSourceDeclaration => symbol.IsSourceDeclaration();
public override bool IsSourceDeclaration => Symbol.IsSourceDeclaration();
/// <summary>
/// Whether this method has type parameters.
/// </summary>
public bool IsGeneric => symbol.IsGenericMethod;
public bool IsGeneric => Symbol.IsGenericMethod;
/// <summary>
/// Whether this method has unbound type parameters.
/// </summary>
public bool IsUnboundGeneric => IsGeneric && SymbolEqualityComparer.Default.Equals(symbol.ConstructedFrom, symbol);
public bool IsUnboundGeneric => IsGeneric && SymbolEqualityComparer.Default.Equals(Symbol.ConstructedFrom, Symbol);
public bool IsBoundGeneric => IsGeneric && !IsUnboundGeneric;
private bool IsReducedExtension => symbol.MethodKind == MethodKind.ReducedExtension;
private bool IsReducedExtension => Symbol.MethodKind == MethodKind.ReducedExtension;
protected IMethodSymbol ConstructedFromSymbol => symbol.ConstructedFrom.ReducedFrom ?? symbol.ConstructedFrom;
protected IMethodSymbol ConstructedFromSymbol => Symbol.ConstructedFrom.ReducedFrom ?? Symbol.ConstructedFrom;
bool IExpressionParentEntity.IsTopLevelParent => true;
@@ -316,19 +316,19 @@ namespace Semmle.Extraction.CSharp.Entities
if (isFullyConstructed)
{
trapFile.constructed_generic(this, Method.Create(Context, ConstructedFromSymbol));
foreach (var tp in symbol.GetAnnotatedTypeArguments())
foreach (var tp in Symbol.GetAnnotatedTypeArguments())
{
trapFile.type_arguments(Type.Create(Context, tp.Symbol), child, this);
child++;
}
var nullability = new Nullability(symbol);
var nullability = new Nullability(Symbol);
if (!nullability.IsOblivious)
trapFile.type_nullability(this, NullabilityEntity.Create(Context, nullability));
}
else
{
foreach (var typeParam in symbol.TypeParameters.Select(tp => TypeParameter.Create(Context, tp)))
foreach (var typeParam in Symbol.TypeParameters.Select(tp => TypeParameter.Create(Context, tp)))
{
trapFile.type_parameters(typeParam, child, this);
child++;
@@ -354,7 +354,7 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateMethodBody(trapFile);
PopulateGenerics(trapFile);
PopulateMetadataHandle(trapFile);
PopulateNullability(trapFile, symbol.GetAnnotatedReturnType());
PopulateNullability(trapFile, Symbol.GetAnnotatedReturnType());
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.PushesLabel;

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override void WriteId(TextWriter trapFile)
{
trapFile.Write(symbol);
trapFile.Write(Symbol);
trapFile.Write(";modifier");
}
@@ -20,7 +20,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override void Populate(TextWriter trapFile)
{
trapFile.modifiers(Label, symbol);
trapFile.modifiers(Label, Symbol);
}
public static string AccessbilityModifier(Accessibility access)

View File

@@ -12,11 +12,11 @@ namespace Semmle.Extraction.CSharp.Entities
public override void Populate(TextWriter trapFile)
{
trapFile.namespaces(this, symbol.Name);
trapFile.namespaces(this, Symbol.Name);
if (symbol.ContainingNamespace != null)
if (Symbol.ContainingNamespace != null)
{
var parent = Create(Context, symbol.ContainingNamespace);
var parent = Create(Context, Symbol.ContainingNamespace);
trapFile.parent_namespace(this, parent);
}
}
@@ -25,11 +25,11 @@ namespace Semmle.Extraction.CSharp.Entities
public override void WriteId(TextWriter trapFile)
{
if (!symbol.IsGlobalNamespace)
if (!Symbol.IsGlobalNamespace)
{
trapFile.WriteSubId(Create(Context, symbol.ContainingNamespace));
trapFile.WriteSubId(Create(Context, Symbol.ContainingNamespace));
trapFile.Write('.');
trapFile.Write(symbol.Name);
trapFile.Write(Symbol.Name);
}
trapFile.Write(";namespace");
}
@@ -47,7 +47,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override int GetHashCode() => QualifiedName.GetHashCode();
private string QualifiedName => symbol.ToDisplayString();
private string QualifiedName => Symbol.ToDisplayString();
public override bool Equals(object obj)
{

View File

@@ -11,20 +11,20 @@ namespace Semmle.Extraction.CSharp.Entities
private OrdinaryMethod(Context cx, IMethodSymbol init)
: base(cx, init) { }
public override string Name => symbol.GetName();
public override string Name => Symbol.GetName();
protected override IMethodSymbol BodyDeclaringSymbol => symbol.PartialImplementationPart ?? symbol;
protected override IMethodSymbol BodyDeclaringSymbol => Symbol.PartialImplementationPart ?? Symbol;
public IMethodSymbol SourceDeclaration
{
get
{
var reducedFrom = symbol.ReducedFrom ?? symbol;
var reducedFrom = Symbol.ReducedFrom ?? Symbol;
return reducedFrom.OriginalDefinition;
}
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => symbol.GetSymbolLocation();
public override Microsoft.CodeAnalysis.Location ReportingLocation => Symbol.GetSymbolLocation();
public override void Populate(TextWriter trapFile)
{
@@ -32,12 +32,12 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateModifiers(trapFile);
ContainingType.PopulateGenerics();
var returnType = Type.Create(Context, symbol.ReturnType);
var returnType = Type.Create(Context, Symbol.ReturnType);
trapFile.methods(this, Name, ContainingType, returnType.TypeRef, OriginalDefinition);
if (IsSourceDeclaration)
{
foreach (var declaration in symbol.DeclaringSyntaxReferences.Select(s => s.GetSyntax()).OfType<MethodDeclarationSyntax>())
foreach (var declaration in Symbol.DeclaringSyntaxReferences.Select(s => s.GetSyntax()).OfType<MethodDeclarationSyntax>())
{
Context.BindComments(this, declaration.Identifier.GetLocation());
TypeMention.Create(Context, declaration.ReturnType, this, returnType);
@@ -49,7 +49,7 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateGenerics(trapFile);
Overrides(trapFile);
ExtractRefReturn(trapFile, symbol, this);
ExtractRefReturn(trapFile, Symbol, this);
ExtractCompilerGenerated(trapFile);
}

View File

@@ -19,7 +19,7 @@ namespace Semmle.Extraction.CSharp.Entities
Original = original ?? this;
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => symbol.GetSymbolLocation();
public override Microsoft.CodeAnalysis.Location ReportingLocation => Symbol.GetSymbolLocation();
public enum Kind
{
@@ -35,9 +35,9 @@ namespace Semmle.Extraction.CSharp.Entities
// actually numbered from 1.
// This is to be consistent from the original (unreduced) extension method.
var isReducedExtension =
symbol.ContainingSymbol is IMethodSymbol method &&
Symbol.ContainingSymbol is IMethodSymbol method &&
method.MethodKind == MethodKind.ReducedExtension;
return symbol.Ordinal + (isReducedExtension ? 1 : 0);
return Symbol.Ordinal + (isReducedExtension ? 1 : 0);
}
}
@@ -45,7 +45,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
get
{
switch (symbol.RefKind)
switch (Symbol.RefKind)
{
case RefKind.Out:
return Kind.Out;
@@ -54,12 +54,12 @@ namespace Semmle.Extraction.CSharp.Entities
case RefKind.In:
return Kind.In;
default:
if (symbol.IsParams)
if (Symbol.IsParams)
return Kind.Params;
if (Ordinal == 0)
{
if (symbol.ContainingSymbol is IMethodSymbol method && method.IsExtensionMethod)
if (Symbol.ContainingSymbol is IMethodSymbol method && method.IsExtensionMethod)
return Kind.This;
}
return Kind.None;
@@ -76,7 +76,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override void WriteId(TextWriter trapFile)
{
if (Parent == null)
Parent = Method.Create(Context, symbol.ContainingSymbol as IMethodSymbol);
Parent = Method.Create(Context, Symbol.ContainingSymbol as IMethodSymbol);
trapFile.WriteSubId(Parent);
trapFile.Write('_');
trapFile.Write(Ordinal);
@@ -92,42 +92,42 @@ namespace Semmle.Extraction.CSharp.Entities
// Very rarely, two parameters have the same name according to the data model.
// This breaks our database constraints.
// Generate an impossible name to ensure that it doesn't conflict.
var conflictingCount = symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < symbol.Ordinal && p.Name == symbol.Name);
return conflictingCount > 0 ? symbol.Name + "`" + conflictingCount : symbol.Name;
var conflictingCount = Symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < Symbol.Ordinal && p.Name == Symbol.Name);
return conflictingCount > 0 ? Symbol.Name + "`" + conflictingCount : Symbol.Name;
}
}
public override void Populate(TextWriter trapFile)
{
PopulateAttributes();
PopulateNullability(trapFile, symbol.GetAnnotatedType());
PopulateRefKind(trapFile, symbol.RefKind);
PopulateNullability(trapFile, Symbol.GetAnnotatedType());
PopulateRefKind(trapFile, Symbol.RefKind);
if (symbol.Name != Original.symbol.Name)
Context.ModelError(symbol, "Inconsistent parameter declaration");
if (Symbol.Name != Original.Symbol.Name)
Context.ModelError(Symbol, "Inconsistent parameter declaration");
var type = Type.Create(Context, symbol.Type);
var type = Type.Create(Context, Symbol.Type);
trapFile.@params(this, Name, type.TypeRef, Ordinal, ParamKind, Parent, Original);
foreach (var l in symbol.Locations)
foreach (var l in Symbol.Locations)
trapFile.param_location(this, Context.CreateLocation(l));
if (!symbol.Locations.Any() &&
symbol.ContainingSymbol is IMethodSymbol ms &&
if (!Symbol.Locations.Any() &&
Symbol.ContainingSymbol is IMethodSymbol ms &&
ms.Name == WellKnownMemberNames.TopLevelStatementsEntryPointMethodName &&
ms.ContainingType.Name == WellKnownMemberNames.TopLevelStatementsEntryPointTypeName)
{
trapFile.param_location(this, Context.CreateLocation());
}
if (!IsSourceDeclaration || !symbol.FromSource())
if (!IsSourceDeclaration || !Symbol.FromSource())
return;
BindComments();
if (IsSourceDeclaration)
{
foreach (var syntax in symbol.DeclaringSyntaxReferences
foreach (var syntax in Symbol.DeclaringSyntaxReferences
.Select(d => d.GetSyntax())
.OfType<ParameterSyntax>()
.Where(s => s.Type != null))
@@ -136,21 +136,21 @@ namespace Semmle.Extraction.CSharp.Entities
}
}
if (symbol.HasExplicitDefaultValue && Context.Defines(symbol))
if (Symbol.HasExplicitDefaultValue && Context.Defines(Symbol))
{
// This is a slight bug in the dbscheme
// We should really define param_default(param, string)
// And use parameter child #0 to encode the default expression.
var defaultValue = GetParameterDefaultValue(symbol);
var defaultValue = GetParameterDefaultValue(Symbol);
if (defaultValue == null)
{
// In case this parameter belongs to an accessor of an indexer, we need
// to get the default value from the corresponding parameter belonging
// to the indexer itself
var method = (IMethodSymbol)symbol.ContainingSymbol;
var method = (IMethodSymbol)Symbol.ContainingSymbol;
if (method != null)
{
var i = method.Parameters.IndexOf(symbol);
var i = method.Parameters.IndexOf(Symbol);
var indexer = (IPropertySymbol)method.AssociatedSymbol;
if (indexer != null)
defaultValue = GetParameterDefaultValue(indexer.Parameters[i]);
@@ -167,7 +167,7 @@ namespace Semmle.Extraction.CSharp.Entities
}
}
public override bool IsSourceDeclaration => symbol.IsSourceDeclaration();
public override bool IsSourceDeclaration => Symbol.IsSourceDeclaration();
bool IExpressionParentEntity.IsTopLevelParent => true;
@@ -239,7 +239,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.param_location(this, GeneratedLocation.Create(Context));
}
protected override int Ordinal => ((Method)Parent).OriginalDefinition.symbol.Parameters.Length;
protected override int Ordinal => ((Method)Parent).OriginalDefinition.Symbol.Parameters.Length;
public override int GetHashCode()
{
@@ -266,20 +266,20 @@ namespace Semmle.Extraction.CSharp.Entities
private readonly ITypeSymbol constructedType;
private ConstructedExtensionParameter(Context cx, Method method, Parameter original)
: base(cx, original.symbol, method, original)
: base(cx, original.Symbol, method, original)
{
constructedType = method.symbol.ReceiverType;
constructedType = method.Symbol.ReceiverType;
}
public override void Populate(TextWriter trapFile)
{
var typeKey = Type.Create(Context, constructedType);
trapFile.@params(this, Original.symbol.Name, typeKey.TypeRef, 0, Kind.This, Parent, Original);
trapFile.@params(this, Original.Symbol.Name, typeKey.TypeRef, 0, Kind.This, Parent, Original);
trapFile.param_location(this, Original.Location);
}
public static ConstructedExtensionParameter Create(Context cx, Method method, Parameter parameter) =>
ExtensionParamFactory.Instance.CreateEntity(cx, (new SymbolEqualityWrapper(parameter.symbol), new SymbolEqualityWrapper(method.symbol.ReceiverType)), (method, parameter));
ExtensionParamFactory.Instance.CreateEntity(cx, (new SymbolEqualityWrapper(parameter.Symbol), new SymbolEqualityWrapper(method.Symbol.ReceiverType)), (method, parameter));
private class ExtensionParamFactory : ICachedEntityFactory<(Method, Parameter), ConstructedExtensionParameter>
{

View File

@@ -22,7 +22,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.directive_elifs(this, trivia.BranchTaken, trivia.ConditionValue, start, index);
Expression.Create(cx, trivia.Condition, this, 0);
Expression.Create(Context, trivia.Condition, this, 0);
}
}
}

Some files were not shown because too many files have changed in this diff Show More