Skip to content

Commit

Permalink
Annotate function arguments (#12641)
Browse files Browse the repository at this point in the history
* Add local inference annotations

---------

Co-authored-by: Volodymyr Agafonkin <[email protected]>
  • Loading branch information
stepankuzmin and mourner authored May 10, 2023
1 parent fff8e0a commit c573f5c
Show file tree
Hide file tree
Showing 102 changed files with 409 additions and 334 deletions.
3 changes: 2 additions & 1 deletion .flowconfig
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@
.*/test/build/downstream-flow-fixture/.*

[version]
0.188.0
0.191.0

[options]
exact_empty_objects=false

[strict]
nonstrict-import
Expand Down
2 changes: 1 addition & 1 deletion bench/benchmarks/expressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ExpressionBenchmark extends Benchmark {
continue;
}

const expressionData = function(rawValue, propertySpec: StylePropertySpecification) {
const expressionData = function(rawValue: any, propertySpec: StylePropertySpecification) {
const rawExpression = convertFunction(rawValue, propertySpec);
const compiledFunction = createFunction(rawValue, propertySpec);
const compiledExpression = createPropertyExpression(rawExpression, propertySpec);
Expand Down
3 changes: 2 additions & 1 deletion bench/benchmarks/worker_transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import TileParser from '../lib/tile_parser.js';
import {OverscaledTileID} from '../../src/source/tile_id.js';
import {serialize, deserialize} from '../../src/util/web_worker_transfer.js';
import {values} from '../../src/util/util.js';
import type {Serialized} from '../../src/util/web_worker_transfer.js';

export default class WorkerTransfer extends Benchmark {
parser: TileParser;
Expand Down Expand Up @@ -81,7 +82,7 @@ export default class WorkerTransfer extends Benchmark {
}
}

function barePayload(obj) {
function barePayload(obj: Serialized) {
// strip all transferables from a worker payload, because we can't transfer them repeatedly in the bench:
// as soon as it's transfered once, it's no longer available on the main thread
return JSON.parse(JSON.stringify(obj, (key, value) => ArrayBuffer.isView(value) ? {} : value) || '{}');
Expand Down
8 changes: 4 additions & 4 deletions build/generate-struct-arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import fs from 'fs';
import ejs from 'ejs';
import {extend} from '../src/util/util.js';
import {createLayout, viewTypes} from '../src/util/struct_array.js';
import type {ViewType, StructArrayLayout} from '../src/util/struct_array.js';
import type {ViewType, StructArrayLayout, StructArrayMember} from '../src/util/struct_array.js';

const structArrayLayoutJs = ejs.compile(fs.readFileSync('src/util/struct_array_layout.js.ejs', 'utf8'), {strict: true});
const structArrayJs = ejs.compile(fs.readFileSync('src/util/struct_array.js.ejs', 'utf8'), {strict: true});
Expand All @@ -33,7 +33,7 @@ const arraysWithStructAccessors = [];
const arrayTypeEntries = new Set();
const layoutCache = {};

function normalizeMembers(members, usedTypes) {
function normalizeMembers(members: Array<StructArrayMember>, usedTypes: Set<string | ViewType>) {
return members.map((member) => {
if (usedTypes && !usedTypes.has(member.type)) {
usedTypes.add(member.type);
Expand Down Expand Up @@ -70,7 +70,7 @@ function createStructArrayType(name: string, layout: StructArrayLayout, includeS
}
}

function createStructArrayLayoutType({members, size, alignment}) {
function createStructArrayLayoutType({members, size, alignment}: StructArrayLayout) {
const usedTypes = new Set(['Uint8']);
members = normalizeMembers(members, usedTypes);

Expand Down Expand Up @@ -106,7 +106,7 @@ function sizeOf(type: ViewType): number {
return viewTypes[type].BYTES_PER_ELEMENT;
}

function camelize (str) {
function camelize (str: string) {
return str.replace(/(?:^|[-_])(.)/g, (_, x) => {
return /^[0-9]$/.test(x) ? _ : x.toUpperCase();
});
Expand Down
3 changes: 2 additions & 1 deletion flow-typed/geojson.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// @flow strict

type GeoJSONPosition = [number, number] | [number, number, number];
type Geometry<T, C> = { type: T, coordinates: C }

declare module "@mapbox/geojson-types" {
declare export type GeoJSONPosition = [number, number] | [number, number, number];

declare export type GeoJSONPoint = Geometry<'Point', GeoJSONPosition>;
declare export type GeoJSONMultiPoint = Geometry<'MultiPoint', Array<GeoJSONPosition>>;

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsdoc": "^39.6.4",
"flow-bin": "0.188.0",
"flow-bin": "0.191.0",
"gl": "6.0.2",
"glob": "^10.0.0",
"is-builtin-module": "^3.2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/data/bucket/circle_bucket.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import type Projection from '../../geo/projection/projection.js';
import type {Vec3} from 'gl-matrix';
import type {IVectorTileLayer} from '@mapbox/vector-tile';

function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {
function addCircleVertex(layoutVertexArray: CircleLayoutArray, x: number, y: number, extrudeX: number, extrudeY: number) {
layoutVertexArray.emplaceBack(
(x * 2) + ((extrudeX + 1) / 2),
(y * 2) + ((extrudeY + 1) / 2));
Expand Down
20 changes: 10 additions & 10 deletions src/data/bucket/fill_extrusion_bucket.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const FACTOR = Math.pow(2, 13);
export const ELEVATION_SCALE = 7.0;
export const ELEVATION_OFFSET = 450;

function addVertex(vertexArray, x, y, nxRatio, nySign, normalUp, top, e) {
function addVertex(vertexArray: FillExtrusionLayoutArray, x: number, y: number, nxRatio: number, nySign: number, normalUp: number, top: number, e: number) {
vertexArray.emplaceBack(
// a_pos_normal_ed:
// Encode top and side/up normal using the least significant bits
Expand All @@ -73,7 +73,7 @@ function addGlobeExtVertex(vertexArray: FillExtrusionExtArray, pos: {x: number,
normal[0] * encode, normal[1] * encode, normal[2] * encode);
}

class PartMetadata {
export class PartMetadata {
acc: Point;
min: Point;
max: Point;
Expand Down Expand Up @@ -661,20 +661,20 @@ class FillExtrusionBucket implements Bucket {
}
}

function getCosHalfAngle(na, nb) {
function getCosHalfAngle(na: Point, nb: Point) {
const nm = na.add(nb)._unit();
const cosHalfAngle = na.x * nm.x + na.y * nm.y;
return cosHalfAngle;
}

function getRoundedEdgeOffset(p0, p1, p2, edgeRadius) {
function getRoundedEdgeOffset(p0: Point, p1: Point, p2: Point, edgeRadius: number) {
const na = p1.sub(p0)._perp()._unit();
const nb = p2.sub(p1)._perp()._unit();
const cosHalfAngle = getCosHalfAngle(na, nb);
return _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius);
}

function _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius) {
function _getRoundedEdgeOffset(p0: Point, p1: Point, p2: Point, cosHalfAngle: number, edgeRadius: number) {
const sinHalfAngle = Math.sqrt(1 - cosHalfAngle * cosHalfAngle);
return Math.min(p0.dist(p1) / 3, p1.dist(p2) / 3, edgeRadius * sinHalfAngle / cosHalfAngle);
}
Expand All @@ -688,14 +688,14 @@ export default FillExtrusionBucket;
// Rendering them twice often results with Z-fighting.
// In case of globe and axis aligned bounds, it is also useful to
// discard edges that have the both endpoints outside the same bound.
function isEdgeOutsideBounds(p1, p2, bounds) {
function isEdgeOutsideBounds(p1: Point, p2: Point, bounds: [Point, Point]) {
return (p1.x < bounds[0].x && p2.x < bounds[0].x) ||
(p1.x > bounds[1].x && p2.x > bounds[1].x) ||
(p1.y < bounds[0].y && p2.y < bounds[0].y) ||
(p1.y > bounds[1].y && p2.y > bounds[1].y);
}

function isEntirelyOutside(ring) {
function isEntirelyOutside(ring: Array<Point>) {
// Discard rings with corners on border if all other vertices are outside: they get defined
// also in the tile across the border. Eventual zero area rings at border are discarded by classifyRings
// and there is no need to handle that case here.
Expand All @@ -713,7 +713,7 @@ function tileToMeter(canonical: CanonicalTileID) {
return circumferenceAtEquator * 2 * exp / (exp * exp + 1) / EXTENT / (1 << canonical.z);
}

function isAOConcaveAngle(p2, p1, p3) {
function isAOConcaveAngle(p2: Point, p1: Point, p3: Point) {
if (p2.x < 0 || p2.x >= EXTENT || p1.x < 0 || p1.x >= EXTENT || p3.x < 0 || p3.x >= EXTENT) {
return false; // angles are not processed for edges that extend over tile borders
}
Expand All @@ -728,7 +728,7 @@ function isAOConcaveAngle(p2, p1, p3) {
return cosAB > -0.866 && dotProductWithNormal < 0;
}

function encodeAOToEdgeDistance(edgeDistance, isConcaveCorner, edgeStart) {
function encodeAOToEdgeDistance(edgeDistance: number, isConcaveCorner: boolean, edgeStart: boolean) {
// Encode concavity and edge start/end using the least significant bits.
// Second least significant bit 1 encodes concavity.
// The least significant bit 1 marks the edge start, 0 for edge end.
Expand Down Expand Up @@ -758,7 +758,7 @@ export function resampleFillExtrusionPolygonsForGlobe(polygons: Point[][][], til
const cellCountOnXAxis = Math.ceil((rightLng - leftLng) / cellCount);
const cellCountOnYAxis = Math.ceil((topLat - bottomLat) / cellCount);

const splitFn = (axis, min, max) => {
const splitFn = (axis: number, min: number, max: number) => {
if (axis === 0) {
return 0.5 * (min + max);
} else {
Expand Down
6 changes: 3 additions & 3 deletions src/data/bucket/symbol_bucket.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ const shaderOpacityAttributes = [
{name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0}
];

function addVertex(array, tileAnchorX, tileAnchorY, ox, oy, tx, ty, sizeVertex, isSDF: boolean, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) {
function addVertex(array: SymbolLayoutArray, tileAnchorX: number, tileAnchorY: number, ox: number, oy: number, tx: number, ty: number, sizeVertex: any, isSDF: boolean, pixelOffsetX: number, pixelOffsetY: number, minFontScaleX: number, minFontScaleY: number) {
const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;
const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;

Expand All @@ -155,7 +155,7 @@ function addVertex(array, tileAnchorX, tileAnchorY, ox, oy, tx, ty, sizeVertex,
);
}

function addGlobeVertex(array, projAnchorX, projAnchorY, projAnchorZ, normX, normY, normZ) {
function addGlobeVertex(array: SymbolGlobeExtArray, projAnchorX: number, projAnchorY: number, projAnchorZ: number, normX: number, normY: number, normZ: number) {
array.emplaceBack(
// a_globe_anchor
projAnchorX,
Expand Down Expand Up @@ -521,7 +521,7 @@ class SymbolBucket implements Bucket {

// cos(11.25 degrees) = 0.98078528056
const cosAngleThreshold = 0.98078528056;
const predicate = (a, b) => {
const predicate = (a: Point, b: Point) => {
const v0 = tileCoordToECEF(a.x, a.y, canonical, 1);
const v1 = tileCoordToECEF(b.x, b.y, canonical, 1);
return vec3.dot(v0, v1) < cosAngleThreshold;
Expand Down
2 changes: 1 addition & 1 deletion src/data/dem_data.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export default class DEMData {
return new RGBAImage({width: this.stride, height: this.stride}, this.pixels);
}

backfillBorder(borderTile: DEMData, dx: number, dy: number) {
backfillBorder(borderTile: DEMData, dx: number, dy: number): void {
if (this.dim !== borderTile.dim) throw new Error('dem dimension mismatch');

let xMin = dx * this.dim,
Expand Down
8 changes: 4 additions & 4 deletions src/data/dem_tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function aabbRayIntersect(min: Vec3, max: Vec3, pos: Vec3, dir: Vec3): ?number {
return tMin;
}

function triangleRayIntersect(ax, ay, az, bx, by, bz, cx, cy, cz, pos: Vec3, dir: Vec3): ?number {
function triangleRayIntersect(ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number, pos: Vec3, dir: Vec3): ?number {
// Compute barycentric coordinates u and v to find the intersection
const abX = bx - ax;
const abY = by - ay;
Expand Down Expand Up @@ -109,11 +109,11 @@ function triangleRayIntersect(ax, ay, az, bx, by, bz, cx, cy, cz, pos: Vec3, dir
return (acX * qvecX + acY * qvecY + acZ * qvecZ) * invDet;
}

function frac(v, lo, hi) {
function frac(v: number, lo: number, hi: number) {
return (v - lo) / (hi - lo);
}

function decodeBounds(x, y, depth, boundsMinx, boundsMiny, boundsMaxx, boundsMaxy, outMin, outMax) {
function decodeBounds(x: number, y: number, depth: number, boundsMinx: number, boundsMiny: number, boundsMaxx: number, boundsMaxy: number, outMin: Array<number>, outMax: Array<number>) {
const scale = 1 << depth;
const rangex = boundsMaxx - boundsMinx;
const rangey = boundsMaxy - boundsMiny;
Expand Down Expand Up @@ -394,7 +394,7 @@ export function buildDemMipmap(dem: DEMData): Array<MipLevel> {
let blockCount = Math.ceil(Math.pow(2, levelCount));
const blockSize = 1 / blockCount;

const blockSamples = (x, y, size, exclusive, outBounds) => {
const blockSamples = (x: number, y: number, size: number, exclusive: boolean, outBounds: Array<number>) => {
const padding = exclusive ? 1 : 0;
const minx = x * size;
const maxx = (x + 1) * size - padding;
Expand Down
7 changes: 4 additions & 3 deletions src/data/feature_index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {DEMSampler} from '../terrain/elevation.js';

import type StyleLayer from '../style/style_layer.js';
import type {QueryFeature} from '../util/vectortile_to_geojson.js';
import type {FeatureStates} from "../source/source_state";
import type {FeatureFilter} from '../style-spec/feature_filter/index.js';
import type Transform from '../geo/transform.js';
import type {FilterSpecification, PromoteIdSpecification} from '../style-spec/types.js';
Expand Down Expand Up @@ -126,7 +127,7 @@ class FeatureIndex {
const transform = args.transform;

const bounds = tilespaceGeometry.bufferedTilespaceBounds;
const queryPredicate = (bx1, by1, bx2, by2) => {
const queryPredicate = (bx1: number, by1: number, bx2: number, by2: number) => {
return polygonIntersectsBox(tilespaceGeometry.bufferedTilespaceGeometry, bx1, by1, bx2, by2);
};
const matching = this.grid.query(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y, queryPredicate);
Expand Down Expand Up @@ -319,13 +320,13 @@ register(FeatureIndex, 'FeatureIndex', {omit: ['rawTileData', 'sourceLayerCoder'

export default FeatureIndex;

function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) {
function evaluateProperties(serializedProperties: mixed, styleLayerProperties: mixed, feature: IVectorTileFeature, featureState: FeatureStates, availableImages: Array<string>) {
return mapObject(serializedProperties, (property, key) => {
const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null;
return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop;
});
}

function topDownFeatureComparator(a, b) {
function topDownFeatureComparator(a: number, b: number) {
return b - a;
}
4 changes: 2 additions & 2 deletions src/data/feature_position_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function getNumericId(value: mixed) {

// custom quicksort that sorts ids, indices and offsets together (by ids)
// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios
function sort(ids, positions, left, right) {
function sort(ids: Float64Array, positions: Uint32Array, left: number, right: number) {
while (left < right) {
const pivot = ids[(left + right) >> 1];
let i = left - 1;
Expand All @@ -120,7 +120,7 @@ function sort(ids, positions, left, right) {
}
}

function swap(arr, i, j) {
function swap(arr: Uint32Array | Float64Array, i: number, j: number) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
Expand Down
2 changes: 1 addition & 1 deletion src/data/load_geometry.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default function loadGeometry(feature: FeatureWithGeometry, canonical?: C
const z2 = 1 << canonical.z;
const {scale, x, y, projection} = tileTransform;

const reproject = (p) => {
const reproject = (p: Point) => {
const lng = lngFromMercatorX((canonical.x + p.x / extent) / z2);
const lat = latFromMercatorY((canonical.y + p.y / extent) / z2);
const p2 = projection.project(lng, lat);
Expand Down
12 changes: 7 additions & 5 deletions src/data/program_configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class SourceExpressionBinder implements AttributeBinder {
this._setPaintValue(start, end, value);
}

_setPaintValue(start, end, value) {
_setPaintValue(start: number, end: number, value: any) {
if (this.type === 'color') {
const color = packColor(value);
for (let i = start; i < end; i++) {
Expand Down Expand Up @@ -258,7 +258,7 @@ class CompositeExpressionBinder implements AttributeBinder, UniformBinder {
this._setPaintValue(start, end, min, max);
}

_setPaintValue(start, end, min, max) {
_setPaintValue(start: number, end: number, min: any, max: any) {
if (this.type === 'color') {
const minColor = packColor(min);
const maxColor = packColor(max);
Expand Down Expand Up @@ -331,7 +331,7 @@ class PatternCompositeBinder implements AttributeBinder {
this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);
}

_setPaintValues(start, end, patterns, positions) {
_setPaintValues(start: number, end: number, patterns: ?string, positions: SpritePositions) {
if (!positions || !patterns) return;

const pos = positions[patterns];
Expand Down Expand Up @@ -639,7 +639,7 @@ const attributeNameExceptions = {
'line-dasharray': ['dash']
};

function paintAttributeNames(property, type) {
function paintAttributeNames(property: string, type: string) {
return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')];
}

Expand Down Expand Up @@ -673,7 +673,9 @@ const defaultLayouts = {
}
};

function layoutType(property, type, binderType) {
type LayoutType = 'array' | 'boolean' | 'color' | 'enum' | 'number' | 'resolvedImage' | 'string';

function layoutType(property: string, type: LayoutType, binderType: string) {
const layoutException = propertyExceptions[property];
// $FlowFixMe[prop-missing] - we don't cover all types in defaultLayouts for some reason
return (layoutException && layoutException[binderType]) || defaultLayouts[type][binderType];
Expand Down
4 changes: 2 additions & 2 deletions src/geo/projection/adjustments.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function getZoomAdjustment(projection: Projection, loc: LngLat) {
return Math.log(scale) / Math.LN2;
}

function getShearAdjustment(projection, zoom, loc, interpT, withoutRotation?: boolean) {
function getShearAdjustment(projection: Projection, zoom: number, loc: LngLat, interpT: number, withoutRotation?: boolean) {

// create two locations a tiny amount (~1km) east and west of the given location
const locw = new LngLat(loc.lng - 180 * offset, loc.lat);
Expand Down Expand Up @@ -141,7 +141,7 @@ function getShearAdjustment(projection, zoom, loc, interpT, withoutRotation?: bo
return shear;
}

function rotate(x, y, angle) {
function rotate(x: number, y: number, angle: number) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return {
Expand Down
2 changes: 1 addition & 1 deletion src/geo/projection/globe_util.js
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ export function globePixelsToTileUnits(zoom: number, id: CanonicalTileID): numbe
return ecefPerPixel * normCoeff;
}

function calculateGlobePosMatrix(x, y, worldSize, lng, lat): Float64Array {
function calculateGlobePosMatrix(x: number, y: number, worldSize: number, lng: number, lat: number): Float64Array {
// transform the globe from reference coordinate space to world space
const scale = globeECEFUnitsToPixelScale(worldSize);
const offset = [x, y, -worldSize / (2.0 * Math.PI)];
Expand Down
Loading

0 comments on commit c573f5c

Please sign in to comment.